Solve in Python:
Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $n$ elements. The $i$-th element is $a_i$ ($i$ = $1, 2, \ldots, n$). He gradually takes the first two leftmost elements from the deque (let's call them $A$ and $B$, respectively), and then does the following: if $A > B$, he writes $A$ to the beginning and writes $B$ to the end of the deque, otherwise, he writes to the beginning $B$, and $A$ writes to the end of the deque. We call this sequence of actions an operation.

For example, if deque was $[2, 3, 4, 5, 1]$, on the operation he will write $B=3$ to the beginning and $A=2$ to the end, so he will get $[3, 4, 5, 1, 2]$.

The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him $q$ queries. Each query consists of the singular number $m_j$ $(j = 1, 2, \ldots, q)$. It is required for each query to answer which two elements he will pull out on the $m_j$-th operation.

Note that the queries are independent and for each query the numbers $A$ and $B$ should be printed in the order in which they will be pulled out of the deque.

Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.

-----Input-----

The first line contains two integers $n$ and $q$ ($2 \leq n \leq 10^5$, $0 \leq q \leq 3 \cdot 10^5$) — the number of elements in the deque and the number of queries. The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$, where $a_i$ $(0 \leq a_i \leq 10^9)$ — the deque element in $i$-th position. The next $q$ lines contain one number each, meaning $m_j$ ($1 \leq m_j \leq 10^{18}$).

-----Output-----

For each teacher's query, output two numbers $A$ and $B$ — the numbers that Valeriy pulls out of the deque for the $m_j$-th operation.

-----Examples-----
Input
5 3
1 2 3 4 5
1
2
10

Output
1 2
2 3
5 2

Input
2 0
0 0

Output

-----Note----- Consider all 10 steps for the first test in detail:...

import sys
input = sys.stdin.readline
from collections import deque

n,q=list(map(int,input().split()))
A=deque(list(map(int,input().split())))
Q=[int(input()) for i in range(q)]

ANS=[0]

for l in range(10**5+1):
    x=A.popleft()
    y=A.popleft()

    ANS.append((x,y))

    if x>y:
        A.appendleft(x)
        A.append(y)
    else:
        A.appendleft(y)
        A.append(x)

ANS0=A[0]
B=list(A)[1:]

for q in Q:
    if q<=10**5+1:
        print(*ANS[q])
    else:
        print(ANS0,B[(q-10**5-2)%(n-1)])


Solve in Python:
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $s = s_1 s_2 \dots s_{n}$ of length $n$ where each letter is either R, S or P.

While initializing, the bot is choosing a starting index $pos$ ($1 \le pos \le n$), and then it can play any number of rounds. In the first round, he chooses "Rock", "Scissors" or "Paper" based on the value of $s_{pos}$:   if $s_{pos}$ is equal to R the bot chooses "Rock";  if $s_{pos}$ is equal to S the bot chooses "Scissors";  if $s_{pos}$ is equal to P the bot chooses "Paper";

In the second round, the bot's choice is based on the value of $s_{pos + 1}$. In the third round — on $s_{pos + 2}$ and so on. After $s_n$ the bot returns to $s_1$ and continues his game.

You plan to play $n$ rounds and you've already figured out the string $s$ but still don't know what is the starting index $pos$. But since the bot's tactic is so boring, you've decided to find $n$ choices to each round to maximize the average number of wins.

In other words, let's suggest your choices are $c_1 c_2 \dots c_n$ and if the bot starts from index $pos$ then you'll win in $win(pos)$ rounds. Find $c_1 c_2 \dots c_n$ such that $\frac{win(1) + win(2) + \dots + win(n)}{n}$ is maximum possible.

-----Input-----

The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases.

Next $t$ lines contain test cases — one per line. The first and only line of each test case contains string $s = s_1 s_2 \dots s_{n}$ ($1 \le n \le 2 \cdot 10^5$; $s_i \in \{\text{R}, \text{S}, \text{P}\}$) — the string of the bot.

It's guaranteed that the total length of all strings in one test doesn't exceed $2 \cdot 10^5$.

-----Output-----

For each test case, print $n$ choices $c_1 c_2 \dots c_n$ to maximize the average number of wins. Print them in the same manner as the string $s$.

If there are multiple optimal answers, print any of...


Solve in Python:
RedDreamer has an array $a$ consisting of $n$ non-negative integers, and an unlucky integer $T$.

Let's denote the misfortune of array $b$ having length $m$ as $f(b)$ — the number of pairs of integers $(i, j)$ such that $1 \le i < j \le m$ and $b_i + b_j = T$. RedDreamer has to paint each element of $a$ into one of two colors, white and black (for each element, the color is chosen independently), and then create two arrays $c$ and $d$ so that all white elements belong to $c$, and all black elements belong to $d$ (it is possible that one of these two arrays becomes empty). RedDreamer wants to paint the elements in such a way that $f(c) + f(d)$ is minimum possible.

For example:

  if $n = 6$, $T = 7$ and $a = [1, 2, 3, 4, 5, 6]$, it is possible to paint the $1$-st, the $4$-th and the $5$-th elements white, and all other elements black. So $c = [1, 4, 5]$, $d = [2, 3, 6]$, and $f(c) + f(d) = 0 + 0 = 0$;  if $n = 3$, $T = 6$ and $a = [3, 3, 3]$, it is possible to paint the $1$-st element white, and all other elements black. So $c = [3]$, $d = [3, 3]$, and $f(c) + f(d) = 0 + 1 = 1$.

Help RedDreamer to paint the array optimally!

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. Then $t$ test cases follow.

The first line of each test case contains two integers $n$ and $T$ ($1 \le n \le 10^5$, $0 \le T \le 10^9$) — the number of elements in the array and the unlucky integer, respectively.

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$) — the elements of the array.

The sum of $n$ over all test cases does not exceed $10^5$.

-----Output-----

For each test case print $n$ integers: $p_1$, $p_2$, ..., $p_n$ (each $p_i$ is either $0$ or $1$) denoting the colors. If $p_i$ is $0$, then $a_i$ is white and belongs to the array $c$, otherwise it is black and belongs to the array $d$.

If there are multiple answers that minimize the value of $f(c) + f(d)$, print any of them.

-----Example-----
Input
2
6 7
1 2 3 4 5 6
3 6
3...

input=__import__('sys').stdin.readline
for _ in range(int(input())):
	n,T=map(int,input().split())
	s=list(map(int,input().split()))
	ans=[0]*n
	g={} # last ind with sum x
	for i in range(n):
		if T-s[i] in g:
			ans[i]=1-ans[g[T-s[i]]]
		g[s[i]]=i
	print(*ans)


Solve in Python:
Reducing Problems - Bug Fixing #8

Oh no! Timmy's reduce is causing problems, Timmy's goal is to calculate the two teams scores and return the winner but timmy has gotten confused and sometimes teams don't enter their scores, total the scores out of 3! Help timmy fix his program!

Return true if team 1 wins or false if team 2 wins!

def calculate_total(t1, t2):
    t1s=sum(t1) if t1 else -1
    t2s=sum(t2) if t2 else -1
    return True if t1s > t2s else False


Solve in Python:
Regex Failure - Bug Fixing #2
Oh no, Timmy's received some hate mail recently but he knows better. Help Timmy fix his regex filter so he can be awesome again!

import re

BAD_WORD = re.compile(r'bad|mean|ugly|horrible|hideous', re.I)

GOOD_WORD = 'awesome'

def filter_words(phrase):
    return BAD_WORD.sub(GOOD_WORD, phrase)


Solve in Python:
Regular Tic-Tac-Toe is boring.

That's why in this Kata you will be playing  Tic-Tac-Toe in **3D** using a 4 x 4 x 4 matrix!

# Kata Task

Play the game. Work out who wins.

Return a string

* `O wins after  moves`
* `X wins after  moves`
* `No winner`

# Rules

* Player `O` always goes first
* Input `moves` is list/array/tuple of `[x,y,z]` (zero based)
* Each player takes a turn until you find a winner, or there are no moves left
* Four of the same symbols in a row wins
* There may be more moves provided than are necessary to finish the game - that is for you to figure out

Good Luck!
DM

def find_winner(grid):
    for x in range(4):
        for y in range(4):
            if grid[x][y][0] and len({grid[x][y][i] for i in range(4)}) == 1:
                return grid[x][y][0]
            if grid[0][x][y] and len({grid[i][x][y] for i in range(4)}) == 1:
                return grid[0][x][y]
            if grid[x][0][y] and len({grid[x][i][y] for i in range(4)}) == 1:
                return grid[x][0][y]
            if x == 0 and grid[0][y][0] and len({grid[i][y][i] for i in range(4)}) == 1:
                return grid[0][y][0]
            if x == 3 and grid[3][y][0] and len({grid[3-i][y][i] for i in range(4)}) == 1:
                return grid[3][y][0]
            if y == 0 and grid[x][0][0] and len({grid[x][i][i] for i in range(4)}) == 1:
                return grid[x][0][0]
            if y == 3 and grid[x][3][0] and len({grid[x][3-i][i] for i in range(4)}) == 1:
                return grid[x][3][0]
    for z in range(4):
        if grid[0][0][z] and len({grid[i][i][z] for i in range(4)}) == 1:
            return grid[0][0][z]
        if grid[3][0][z] and len({grid[3-i][i][z] for i in range(4)}) == 1:
            return grid[3][0][z]
    if grid[0][0][0] and len({grid[i][i][i] for i in range(4)}) == 1:
        return grid[0][0][0]
    if grid[0][3][0] and len({grid[i][3-i][i] for i in range(4)}) == 1:
        return grid[0][3][0]
    if grid[0][0][3] and len({grid[i][i][3-i] for i in range(4)}) == 1:
        return grid[0][0][3]
    if grid[0][3][3] and len({grid[i][3-i][3-i] for i in range(4)}) == 1:
        return grid[0][3][3]

def play_OX_3D(moves):
    grid = [[[None for _ in range(4)] for _ in range(4)] for _ in range(4)]

    players = ['O', 'X']

    for i, (x, y, z) in enumerate(moves):
        player = players[i%len(players)]
        grid[x][y][z] = player
        winner = find_winner(grid)

        if winner:
            return f'{player} wins after {i+1} moves'

    return 'No winner'


Solve in Python:
Related to MrZizoScream's Product Array kata. You might want to solve that one first :)

```if:javascript
**Note:** Node 10 has now been enabled, and you can now use its BigInt capabilities if you wish, though your resulting array must still contain strings (e.g. "99999999999", not 9999999999n)

Pre-node 10: You will need to use the BigNumber.js library! Please use `.toFixed(0)` or `.toPrecision()` to round instead of `.toString(10)`, as the latter is _very_ slow
```

This is an adaptation of a problem I came across on LeetCode.

Given an array of numbers, your task is to return a new array where each index (`new_array[i]`) is equal to the product of the original array, except for the number at that index (`array[i]`).

**Two things to keep in mind:**

* Zeroes will be making their way into some of the arrays you are given
* O(n^2) solutions will not pass.

Examples:

**Note**: All inputs will be valid arrays of nonzero length.

Have fun! Please upvote if you enjoyed :)

def product_sans_n(l):
    contains_zeroes = False
    product = 1
    for n in l:
        if n:
            product *= n
        elif not contains_zeroes:
            contains_zeroes = True
        else:
            return [0] * len(l)
    return [0 if n else product for n in l] if contains_zeroes else [product // n for n in l]


Solve in Python:
Remember the game 2048?

The main part of this game is merging identical tiles in a row.

* Implement a function that models the process of merging all of the tile values in a single row.
* This function takes the array line as a parameter and returns a new array with the tile values from line slid towards the front of the array (index 0) and merged.
* A given tile can only merge once.
* Empty grid squares are represented as zeros.
* Your function should work on arrays containing arbitrary number of elements.

## Examples

```
merge([2,0,2,2])  -->  [4,2,0,0]
```

Another example with repeated merges:

```
merge([4,4,8,16])  -->  [8,8,16,0]
merge([8,8,16,0])  -->  [16,16,0,0]
merge([16,16,0,0]) -->  [32,0,0,0]
```

def merge(a):
    a = [i for i in a if i] + [i for i in a if not i]
    for i in range(len(a) - 1):
        if a[i] == a[i+1]: a[i], a[i+1] = 2 * a[i], 0

    return [i for i in a if i] + [i for i in a if not i]


Solve in Python:
Remember the movie with David Bowie: 'The Labyrinth'?

You can remember your childhood here: https://www.youtube.com/watch?v=2dgmgub8mHw

In this scene the girl is faced with two 'Knights" and two doors. One door leads the castle where the Goblin King and her kid brother is, the other leads to certain death. She can ask the 'Knights'  a question to find out which door is the right one to go in. But...

One of them always tells the truth, and the other one always lies.

In this Kata one of the 'Knights' is on a coffee break, leaving the other one to watch the doors. You have to determine if the one there is the Knight(Truth teller) or Knave(Liar) based off of what he ```says```

Create a function:
```
def knight_or_knave(says):
  # returns if knight or knave
```
Your function should determine if the input '''says''' is True or False and then return:
```'Knight!'``` if True or ```'Knave! Do not trust.'``` if False

Input will be either boolean values, or strings.
The strings will be simple statements that will be either true or false, or evaluate to True or False.

See example test cases for, well... examples

You will porbably need to ```eval(says)```

But note: Eval is evil, and is only here for this Kata as a game.

And remember the number one rule of The Labyrinth, even if it is easy, Don't ever say 'that was easy.'

def knight_or_knave(said):
    return "Knight!" if eval(str(said)) else "Knave! Do not trust."


Solve in Python:
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.

 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.

Example 1:

Input: [1,1,2,2,2]
Output: true

Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.

Example 2:

Input: [3,3,3,3,4]
Output: false

Explanation: You cannot find a way to form a square with all the matchsticks.

Note:

The length sum of the given matchsticks is in the range of 0 to 10^9.
The length of the given matchstick array will not exceed 15.

class Solution:
     def makesquare(self, nums):
         s = sum(nums)
         if not s % 4 == 0:
             return False
         l = s // 4
         from collections import Counter
         self.c = Counter(nums)
         for _ in range(4):
             n = self.f(0, sorted(self.c.elements(),reverse=True), l, ())
             if not n:
                 return False
             self.c.subtract(n)
         return True

     def f(self, index, keys, sum, nums):
         if sum == 0:
             return nums
         if sum < 0 or index >= len(keys):
             return None
         return self.f(index + 1, keys, sum - keys[index], (*nums, keys[index])) \
                or self.f(index + 1, keys, sum, nums)


Solve in Python:
Reminder: the median of the array $[a_1, a_2, \dots, a_{2k+1}]$ of odd number of elements is defined as follows: let $[b_1, b_2, \dots, b_{2k+1}]$ be the elements of the array in the sorted order. Then median of this array is equal to $b_{k+1}$.

There are $2n$ students, the $i$-th student has skill level $a_i$. It's not guaranteed that all skill levels are distinct.

Let's define skill level of a class as the median of skill levels of students of the class.

As a principal of the school, you would like to assign each student to one of the $2$ classes such that each class has odd number of students (not divisible by $2$). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.

What is the minimum possible absolute difference you can achieve?

-----Input-----

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) — the number of students halved.

The second line of each test case contains $2n$ integers $a_1, a_2, \dots, a_{2 n}$ ($1 \le a_i \le 10^9$) — skill levels of students.

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.

-----Output-----

For each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.

-----Example-----
Input
3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16

Output
0
1
5

-----Note-----

In the first test, there is only one way to partition students — one in each class. The absolute difference of the skill levels will be $|1 - 1| = 0$.

In the second test, one of the possible partitions is to make the first class of students with skill levels $[6, 4, 2]$, so that the skill level of the...

def main():
    def solve():

        n = int(input())
        aa = [int(a) for a in input().split()]
        aa.sort()
        print(aa[n] - aa[n-1])

    q = int(input())
    for _ in range(q):
        solve()

def __starting_point():
    main()
__starting_point()


Solve in Python:
Remove the parentheses
=
In this kata you are given a string for example:

```python
"example(unwanted thing)example"
```

Your task is to remove everything inside the parentheses as well as the parentheses themselves.

The example above would return:

```python
"exampleexample"
```

Other than parentheses only letters and spaces can occur in the string. Don't worry about other brackets like ```"[]"``` and ```"{}"``` as these will never appear.

def remove_parentheses(s):
    s2 = s.replace('(','|').replace(')','|')
    level = 0
    start = 0
    i = s2.find('|')
    while i != -1:
        if s[i] == '(':
            if (level == 0):
                start = i
            level += 1
        elif s[i] == ')':
            level -= 1
            if (level == 0):
                s = s[0:start]+s[i+1:]
                s2 = s2[0:start]+s2[i+1:]
                i = -1
        i = s2.find('|',i+1)
    return s

print((remove_parentheses("example(unwanted thing)example")))


def multiple_of_index(arr):
    return [v for i,v in enumerate(arr[1:]) if v%(i+1) == 0]


Solve in Python:
Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k.
Note that every number in the answer must not have leading zeros except for the number 0 itself. For example, 01 has one leading zero and is invalid, but 0 is valid.
You may return the answer in any order.

Example 1:
Input: n = 3, k = 7
Output: [181,292,707,818,929]
Explanation: Note that 070 is not a valid number, because it has leading zeroes.

Example 2:
Input: n = 2, k = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

Example 3:
Input: n = 2, k = 0
Output: [11,22,33,44,55,66,77,88,99]

Example 4:
Input: n = 2, k = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

Example 5:
Input: n = 2, k = 2
Output: [13,20,24,31,35,42,46,53,57,64,68,75,79,86,97]

Constraints:

2 <= n <= 9
0 <= k <= 9

class Solution:
    def numsSameConsecDiff(self, N: int, K: int) -> List[int]:

        def dfs(N, K, digit, rst):
            if not N:
                rst.append(int(''.join(map(str, digit)))); return
            if digit[-1] + K <= 9:
                dfs(N-1, K, digit + [digit[-1] + K], rst)
            if digit[-1] - K >= 0:
                dfs(N-1, K, digit + [digit[-1] - K], rst)

        if N == 1: return list(range(10))
        if K == 0: return [int(str(i) * N) for i in range(1, 10)]
        rst = []
        for i in range(1, 10):
            dfs(N-1, K, [i], rst)
        return rst


Solve in Python:
Return an output string that translates an input string `s`/`$s` by replacing each character in `s`/`$s` with a number representing the number of times that character occurs in `s`/`$s` and separating each number with the character(s) `sep`/`$sep`.

def freq_seq(s, sep):
    freq = {}
    newStr = []
    for i in s:
        if freq.get(i) == None:
            freq[i] = 1
        else:
            freq[i] += 1
    for i in s:
        newStr.append(str(freq[i]))
    return sep.join(newStr)


Solve in Python:
Return the Nth Even Number

The input will not be 0.

def nth_even(n):
    '''
    input: n, positive integer
    output: n-th even number (0 is first, 2 is second, 4 is third etc.)
    '''
    return (n - 1) * 2


Solve in Python:
Return the `n`th term of the Recamán's sequence.

```
a(0) = 0;

        a(n-1) - n, if this value is positive and not yet in the sequence
      /
a(n) <
      \
        a(n-1) + n, otherwise
```

___

A video about Recamán's sequence by Numberphile: https://www.youtube.com/watch?v=FGC5TdIiT9U

def recaman(n):
    seq = [0]
    seen = {0}
    for i in range(1, n+1):
        x = seq[-1] - i
        if x < 0 or x in seen:
            x = seq[-1] + i
        seq.append(x)
        seen.add(x)
    return seq[-1]


Solve in Python:
Return the century of the input year. The input will always be a 4 digit string, so there is no need for validation.

### Examples
```
"1999" --> "20th"
"2011" --> "21st"
"2154" --> "22nd"
"2259" --> "23rd"
"1124" --> "12th"
"2000" --> "20th"
```

SUFFIX_ONE = 'st'
SUFFIX_TWO = 'nd'
SUFFIX_THREE = 'rd'
SUFFIX_OTHER = 'th'

def what_century(year):
    century = 1 + (int(year) - 1) // 100
    return str(century) + ordinal_suffix(century)

def ordinal_suffix(number):
    if number // 10 == 1:   # ten or teen
        return SUFFIX_OTHER
    elif number % 10 == 1:  # ending 1
        return SUFFIX_ONE
    elif number % 10 == 2:  # ending 2
        return SUFFIX_TWO
    elif number % 10 == 3:  # ending 3
        return SUFFIX_THREE
    else:
        return SUFFIX_OTHER


Solve in Python:
Return the largest possible k such that there exists a_1, a_2, ..., a_k such that:

Each a_i is a non-empty string;
Their concatenation a_1 + a_2 + ... + a_k is equal to text;
For all 1 <= i <= k,  a_i = a_{k+1 - i}.

Example 1:
Input: text = "ghiabcdefhelloadamhelloabcdefghi"
Output: 7
Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".

Example 2:
Input: text = "merchant"
Output: 1
Explanation: We can split the string on "(merchant)".

Example 3:
Input: text = "antaprezatepzapreanta"
Output: 11
Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)".

Example 4:
Input: text = "aaa"
Output: 3
Explanation: We can split the string on "(a)(a)(a)".

Constraints:

text consists only of lowercase English characters.
1 <= text.length <= 1000

from collections import deque

class Solution:
    def longestDecomposition(self, text: str) -> int:
        def check(a, b):
            return all([a[i] == b[i] for i in range(len(a))])

        ans = 0
        l, r = deque([]), deque([])
        for i in range(len(text) // 2):
            l.append(text[i])
            r.appendleft(text[-1 - i])
            if check(l, r):
                ans += 2
                l, r = deque([]), deque([])
        if len(text) % 2 == 0 and len(l) == len(r) == 0:
            return ans
        else:
            return ans + 1


Solve in Python:
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.
If there is no non-empty subarray with sum at least K, return -1.

Example 1:
Input: A = [1], K = 1
Output: 1

Example 2:
Input: A = [1,2], K = 4
Output: -1

Example 3:
Input: A = [2,-1,2], K = 3
Output: 3

Note:

1 <= A.length <= 50000
-10 ^ 5 <= A[i] <= 10 ^ 5
1 <= K <= 10 ^ 9

class Solution:
    def shortestSubarray(self, A: List[int], K: int) -> int:

        preSum = [0]
        for e in A:
            preSum.append(preSum[-1] + e)

        min_len = sys.maxsize

        #0 2 1 3 7

        #0 1 3 7

        q = collections.deque([])
        for i in range(len(preSum)):
            while q and preSum[q[-1]] > preSum[i]:
                q.pop()
            while q and preSum[i] - K >= preSum[q[0]]:
                min_len = min(min_len, i-q.popleft())

            q.append(i)

        return min_len if min_len != sys.maxsize else -1


Solve in Python:
Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).

Example 1:
Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".

Example 2:
Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".

Constraints:

1 <= text.length <= 2000
text has only lowercase English letters.

class Solution:
    def distinctEchoSubstrings(self, text: str) -> int:
        def check(s):return s[:len(s)//2]==s[len(s)//2:]
        ret = set()
        n = len(text)
        for l in range(2,n+1,2):
            for start in range(n-l+1):
                s=text[start:start+l]
                if check(text[start:start+l]): ret.add(s)
        # print(ret)
        return len(ret)


Solve in Python:
Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)
(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.)
Since the answer may be large, return the answer modulo 10^9 + 7.

Example 1:
Input: n = 5
Output: 12
Explanation: 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.

Example 2:
Input: n = 100
Output: 682289015

Constraints:

1 <= n <= 100

class Solution:
    def numPrimeArrangements(self, n: int) -> int:
        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]
        r = sum(1 for p in primes if p <= n)
        a = 10**9 + 7
        ans = 1
        for i in range(1, min(r, n-r)+1):
            ans *= (i % a)**2
            ans %= a
        for i in range(min(r, n-r)+1, max(r, n-r)+1):
            ans *= i
            ans %= a
        return ans


Solve in Python:
Return the root node of a binary search tree that matches the given preorder traversal.
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val.  Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)
It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.
Example 1:
Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

Constraints:

1 <= preorder.length <= 100
1 <= preorder[i] <= 10^8
The values of preorder are distinct.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:

        if len(preorder) == 0:
            return None

        return self.helper(preorder,0,len(preorder))

    def helper(self,preorder,start,end):
        # print(start,end,preorder[start:end])
        if start >= end:
            return None

        split = start + 1
        root = TreeNode(preorder[start])

        while split < end and preorder[start] > preorder[split]:
            split+=1

        root.left = self.helper(preorder,start + 1,split)
        root.right = self.helper(preorder,split,end)
        return root


Solve in Python:
Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

class Solution:
     def reverseBetween(self, head, m, n):
         """
         :type head: ListNode
         :type m: int
         :type n: int
         :rtype: ListNode
         """
         if n == 1:
             return head

         sentinel = ListNode(0)
         pre = sentinel
         pre.next = head
         end = head
         while m > 1:
             pre = pre.__next__
             m -= 1
         while n:
             end = end.__next__
             n -= 1
         # print(pre.val)
         # print(end.val) if end else print("None")
         new_start = self.reverse(pre.__next__, end)
         pre.next = new_start
         return sentinel.__next__

     def reverse(self, cur, end):
         new_head = end
         while cur != end:
             next = cur.__next__
             cur.next = new_head
             new_head = cur
             cur = next
             # print(new_head.val) if new_head else print("none")
         return new_head


Solve in Python:
Reverse and invert all integer values in a given list.

Python:

    reverse_invert([1,12,'a',3.4,87,99.9,-42,50,5.6]) = [-1,-21,-78,24,-5]

Ignore all other types than integer.

reverse_invert=lambda l: [(-1 if n>0 else 1)*int(str(abs(n))[::-1]) for n in l if type(n)==int]


Solve in Python:
Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this kata.

def reverse_alternate(s):
  words = s.split()
  words[1::2] = [word[::-1] for word in words[1::2]]
  return ' '.join(words)


Solve in Python:
Richik$Richik$ has just completed his engineering and has got a job in one of the firms at Sabrina$Sabrina$ which is ranked among the top seven islands in the world in terms of the pay scale.
Since Richik$Richik$ has to travel a lot to reach the firm, the owner assigns him a number X$X$, and asks him to come to work only on the day which is a multiple of X$X$. Richik joins the firm on 1-st day but starts working from X-th day. Richik$Richik$ is paid exactly the same amount in Dollars as the day number. For example, if Richik$Richik$ has been assigned X=3$X = 3$, then he will be paid 3$3$ dollars and 6$6$ dollars on the 3rd$3rd$ and 6th$6th$ day on which he comes for work.
On N−th$N-th$ day, the owner calls up Richik$Richik$ and asks him not to come to his firm anymore. Hence Richik$Richik$ demands his salary of all his working days together. Since it will take a lot of time to add, Richik$Richik$ asks help from people around him, let's see if you can help him out.

-----Input:-----
- First line will contain T$T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, two integers X,N$X, N$.

-----Output:-----
For each testcase, output in a single line which is the salary which Richik$Richik$ demands.

-----Constraints-----
- 1≤T≤1000$1 \leq T \leq 1000$
- 1≤X<=N≤107$1 \leq X<=N \leq 10^7$

-----Sample Input:-----
1
3 10

-----Sample Output:-----
18

T=int(input())
for i in range(T):
    X,N=list(map(int,input().split()))
    a=N//X
    if(N%X!=0):
        S=(2*X+(a-1)*X)*(a/2)
    else:
        S=(2*X+(a-2)*X)*((a-1)/2)
    print(int(S))


Solve in Python:
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.

In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario. [Image]

Each one of them has a set of numbers between 1 and n - 1 (inclusive). Rick's set is s_1 with k_1 elements and Morty's is s_2 with k_2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins.

Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.

-----Input-----

The first line of input contains a single integer n (2 ≤ n ≤ 7000) — number of objects in game.

The second line contains integer k_1 followed by k_1 distinct integers s_{1, 1}, s_{1, 2}, ..., s_{1, }k_1 — Rick's set.

The third line contains integer k_2 followed by k_2 distinct integers s_{2, 1}, s_{2, 2}, ..., s_{2, }k_2 — Morty's set

1 ≤ k_{i} ≤ n - 1 and 1 ≤ s_{i}, 1, s_{i}, 2, ..., s_{i}, k_{i} ≤ n - 1 for 1 ≤ i ≤ 2.

-----Output-----

In the first line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end.

Similarly, in the second...

RESULT = ['Lose', 'Loop', 'Win']

class Player(object):
    """docstring for Player"""
    def __init__(self):
        super(Player, self).__init__()
        self.a = list(map(int, input().split()))[1:]
        self.f = [len(self.a)] * n
        self.f[0] = 0

    def prev(self, i):
        for x in self.a:
            if self.f[(i - x) % n] > 0:
                yield (i - x) % n

    def print_result(self):
        print(*[RESULT[min(x, 1)] for x in self.f[1:]])

n = int(input())
a, b = Player(), Player()
q = [(a, b, 0), (b, a, 0)]
while q:
    x, y, i = q.pop()
    for j in y.prev(i):
        y.f[j] = -1
        for k in x.prev(j):
            x.f[k] -= 1
            if x.f[k] == 0:
                q.append((x, y, k))

a.print_result()
b.print_result()


Solve in Python:
Rick wants a faster way to get the product of the largest pair in an array. Your task is to create a performant solution to find the product of the largest two integers in a unique array of positive numbers. All inputs will be valid.
Passing [2, 6, 3] should return 18, the product of [6, 3].

```Disclaimer: Mr. Roll will only accept solutions that are faster than his, which has a running time O(nlogn).```

```python
max_product([2, 1, 5, 0, 4, 3])              # => 20
max_product([7, 8, 9])                       # => 72
max_product([33, 231, 454, 11, 9, 99, 57])   # => 104874
```

import heapq

def max_product(a):
    first, second = heapq.nlargest(2, a)
    return first * second


Solve in Python:
Ripul was skilled in the art of lapidary. He used to collect stones and convert it into decorative items for sale.  There were n stone shops. Each shop was having one exclusive stone of value s[i] , where 1<=i<=n.  If number of stones collected are more than 1, then total value will be product of values of all the stones he collected. Ripul wants to have maximum value of stones he collected. Help Ripul in picking up the subarray which leads to maximum value of stones he collected.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- The first line of each testcase contains an integer $N$, denoting number of elements in the given array.
- The second line contains $N$ space-separated integers $S1$, $S2$, …, $SN$ denoting the value of stone in each shop.

-----Output:-----
For each testcase, output the maximum value of stones possible, the starting index and ending index of the chosen subarray (0-based indexing). If there are multiple subarrays with same value, print the one with greater starting index. If there are multiple answer subarrays with same starting index, print the one with greater ending index. (The answer will fit in 64 bit binary number).

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 10^5$
- $-100 \leq S[i] \leq 100$

-----Subtasks-----
- 30 points : $1 \leq N \leq 10^3$
- 70 points : $1 \leq N \leq 10^5$

-----Sample Input:-----
1
3

1 2 3

-----Sample Output:-----
6 1 2

-----EXPLANATION:-----
If Ripul collects all the all the three gems, total value will be 6 (1 * 2 * 3).
If Ripul collects last two gems, total value will be 6 (1 * 2 * 3).
So, he picks the subarray with greater starting index.

t=int(input())
while(t):
 t=t-1
 n=int(input())
 S=list(map(int,input().split()))
 max1=-1*float("inf")
 for i in range(len(S)):
  p = 1
  for j in range(i,len(S)):
   p = p * S[j]
   if max1 <= p:
    s_i = i
    s_f = j
    max1 = p
 print(max1,s_i,s_f)


Solve in Python:
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.

His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)

From that point A he walks the distance `d` multiplied by a constant `distmult` on a line that
has the angle `ang` multiplied by a constant `angmult` and so on and on.

We have `d0 = d`, `ang0 = ang`; then `d1 = d * distmult`, `ang1 = ang * angmult` etc ...

Let us suppose he follows this process n times.
What are the coordinates `lastx, lasty` of the last point?

The function `crusoe` has parameters;
- n        : numbers of steps in the process
- d        : initial chosen distance
- ang      : initial chosen angle in degrees
- distmult : constant multiplier of the previous distance
- angmult  : constant multiplier of the previous angle

`crusoe(n, d, ang, distmult, angmult)` should return
`lastx, lasty` as an array or a tuple depending on the language.

### Example:
`crusoe(5, 0.2, 30, 1.02, 1.1)` ->

The successive `x` are : `0.0, 0.173205, 0.344294, 0.511991, 0.674744, 0.830674` (approximately)

The successive `y` are : `0.0, 0.1, 0.211106, 0.334292, 0.47052, 0.620695` (approximately)

and
```
lastx: 0.8306737544381833
lasty: 0.620694691344071
```
### A drawing:

![alternative text](https://i.imgur.com/SGHbb6Vl.png)

Successive points:

- x: `0.0, 0.9659..., 1.8319..., 2.3319..., 1.8319...`
- y: `0.0, 0.2588..., 0.7588..., 1.6248..., 2.4908...`

### Note
Please could you ask before translating: some translations are already written and published when/if the kata is approved.

from math import cos, sin, radians

def crusoe(n, d, ang, dist_mult, ang_mult):
    x, y, a = 0, 0, radians(ang)
    for i in range(n):
        x += d * cos(a)
        y += d * sin(a)
        d *= dist_mult
        a *= ang_mult
    return x, y


Solve in Python:
Rodriguez is a happy and content farmer. He has got a square field of side length $x$. Miguel, his son has himself grown into a man and his father wants to gift him something out of which he can make a living. So he gift's his son a square piece of land cut out from a corner of his field of side length $ y (y < x) $ leaving him with a L-shaped land.
But in Spanish tradition, it is considered inauspicious to own something which is prime in number. This worries Rodriguez as he doesn't want his left out area to be a prime number leading to bad luck. Find whether the spilt will be in terms with the tradition leaving Rodriguez happy.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains two integers $x, y$.

-----Output:-----
Print YES if Rodriguez will be happy. Otherwise print NO.

-----Constraints-----
- $1 \leq T \leq 5$
- $1 \leq y < x \leq 100000000000$

-----Sample Input:-----
2
7 5
6 5

-----Sample Output:-----
YES
NO

-----EXPLANATION:-----
In case 1 :
Left out area is 24, which is not prime.
In case 2:
Left out area is 11, which is prime.

from math import sqrt
def isPrime(n):
 for i in range(2, int(sqrt(n))+1):
  if(n%i==0): return True
 return False
ans = []
for _ in range(int(input())):
 x, y = map(int, input().split())
 ans.append('NO' if(isPrime(x**2-y**2)) else 'YES')
print('\n'.join(ans))


Solve in Python:
Roger is a robot. He has an arm that is a series of n segments connected to each other. The endpoints of the i-th segment are initially located at points (i - 1, 0) and (i, 0). The endpoint at (i - 1, 0) is colored red and the endpoint at (i, 0) is colored blue for all segments. Thus, the blue endpoint of the i-th segment is touching the red endpoint of the (i + 1)-th segment for all valid i.

Roger can move his arm in two different ways:   He can choose some segment and some value. This is denoted as choosing the segment number i and picking some positive l. This change happens as follows: the red endpoint of segment number i and segments from 1 to i - 1 are all fixed in place. Imagine a ray from the red endpoint to the blue endpoint. The blue endpoint and segments i + 1 through n are translated l units in the direction of this ray.

 [Image] [Image]

In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B gets translated.

 He can choose a segment and rotate it. This is denoted as choosing the segment number i, and an angle a. The red endpoint of the i-th segment will stay fixed in place. The blue endpoint of that segment and segments i + 1 to n will rotate clockwise by an angle of a degrees around the red endpoint.

 [Image] [Image]

In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B get rotated around point A.

Roger will move his arm m times. These transformations are a bit complicated, and Roger easily loses track of where the blue endpoint of the last segment is. Help him compute the coordinates of the blue endpoint of the last segment after applying each operation. Note that these operations are cumulative, and Roger's arm may intersect itself arbitrarily during the moves.

-----Input-----

The first line of the input will contain two integers n and m (1 ≤ n, m ≤ 300 000) — the number of segments and the number of operations to perform.

Each of...

from cmath import rect
import sys
import math
from functools import reduce

class SegmentTree():
    def __init__(self, L, function = lambda x,y: x+y):
        self.function = function
        N = self.size = len(L)
        M = 1 << N.bit_length()
        self.margin = 2*M - N
        self.L = [None for i in range(self.margin)] + L
        for i in range(M-1, 0, -1):
            x, y = self.L[i<<1], self.L[i<<1|1]
            self.L[i] = None if x is None or y is None else function(x, y)
    def modify(self, pos, value):
        p = pos + self.margin
        self.L[p] = value
        while p > 1:
            x, y = self.L[p], self.L[p^1]
            if p&1: x, y = y, x
            self.L[p>>1] = None if x is None or y is None else self.function(x, y)
            p>>=1
    def query(self, left, right):
        l, r = left + self.margin, right + self.margin
        stack = []
        void = True
        while l < r:
            if l&1:
                if void:
                    result = self.L[l]
                    void = False
                else:
                    result = self.function(result, self.L[l])
                l+=1
            if r&1:
                r-=1
                stack.append(self.L[r])
            l>>=1
            r>>=1
        init = stack.pop() if void else result
        return reduce(self.function, reversed(stack), init)

def degrect(r, phi):
    return rect(r, math.radians(phi))

def vsum(u, v): #u = (x + y*1j, phi)
    return (u[0] + v[0]*degrect(1, u[1]), (u[1] + v[1])%360)

def solve(f):
    n, m = [int(x) for x in f.readline().split()]
    segments = [[1,0] for i in range(n)]
    arm = SegmentTree([(1,0) for i in range(n)], vsum)
    for line in f:
        q, i, a = [int(x) for x in line.split()]
        if q == 1:
            segments[i-1][0] += a
        else:
            segments[i-1][1] -= a
        arm.modify(i-1, (degrect(segments[i-1][0], segments[i-1][1]), segments[i-1][1]))
        query = arm.query(0,n)[0]
        print(query.real, query.imag)

solve(sys.stdin)


Solve in Python:
Roger recently built a circular race track with length K$K$. After hosting a few races, he realised that people do not come there to see the race itself, they come to see racers crash into each other (what's wrong with our generation…). After this realisation, Roger decided to hold a different kind of "races": he hired N$N$ racers (numbered 1$1$ through N$N$) whose task is to crash into each other.
At the beginning, for each valid i$i$, the i$i$-th racer is Xi$X_i$ metres away from the starting point of the track (measured in the clockwise direction) and driving in the direction Di$D_i$ (clockwise or counterclockwise). All racers move with the constant speed 1$1$ metre per second. The lengths of cars are negligible, but the track is only wide enough for one car, so whenever two cars have the same position along the track, they crash into each other and the direction of movement of each of these cars changes (from clockwise to counterclockwise and vice versa). The cars do not change the directions of their movement otherwise.
Since crashes reduce the lifetime of the racing cars, Roger sometimes wonders how many crashes happen. You should answer Q$Q$ queries. In each query, you are given an integer T$T$ and you should find the number of crashes that happen until T$T$ seconds have passed (inclusive).

-----Input-----
- The first line of the input contains three space-separated integers N$N$, Q$Q$ and K$K$.
- N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains two space-separated integers Di$D_i$ and Xi$X_i$, where Di=1$D_i = 1$ and Di=2$D_i = 2$ denote the clockwise and counterclockwise directions respectively.
- Each of the next Q$Q$ lines contain a single integer T$T$ describing a query.

-----Output-----
For each query, print a single line containing one integer — the number of crashes.

-----Constraints-----
- 1≤N≤105$1 \le N \le 10^5$
- 1≤Q≤1,000$1 \le Q \le 1,000$
- 1≤K≤1012$1 \le K \le 10^{12}$
- 1≤Di≤2$1 \le D_i \le 2$ for each valid i$i$
- 0≤Xi≤K−1$0 \le X_i \le...

import numpy as np
from numba import njit
i8 = np.int64

@njit
def solve(a, b, t, K, N):
    t1 = t // K
    d = t % K * 2
    # b が a から a + d の位置にあれば衝突する
    x = 0
    y = 0
    ans = 0
    for c in a:
        while b[x] < c:
            x += 1
        while b[y] <= c + d:
            y += 1
        ans += y - x
    ans += t1 * len(a) * (N - len(a)) * 2
    return ans

def set_ini(DX, K):
    a = DX[1][DX[0] == 1]
    a = np.sort(a)
    b = DX[1][DX[0] == 2]
    b = np.sort(b)
    b = np.hstack((b, b + K, b + 2 * K, [3 * K]))
    return a, b

def main():
    f = open('/dev/stdin', 'rb')
    vin = np.fromstring(f.read(), i8, sep=' ')
    N, Q, K = vin[0:3]
    head = 3
    DX = vin[head:head + 2*N].reshape(-1, 2).T
    a, b = set_ini(DX, K)
    head += 2 * N
    T = vin[head: head + Q]
    for t in T:
        print(solve(a, b, t, K, N))

def __starting_point():
    main()
__starting_point()


Solve in Python:
Rohit collects coins: he has exactly one coin for every year from 1 to n. Naturally, Rohit keeps all the coins in his collection in the order in which they were released. Once Rohit's younger brother made a change — he took all the coins whose release year dated from l to r inclusively and put them in the reverse order. That is, he took a certain segment [l, r] and reversed it. At that, the segment's endpoints did not coincide. For example, if n = 8, then initially Rohit's coins were kept in the order 1 2 3 4 5 6 7 8. If Rohit's younger brother chose the segment [2, 6], then after the reversal the coin order will change to 1 6 5 4 3 2 7 8. Rohit suspects that someone else could have spoilt the permutation after his brother. Help him to find that out. Check if the given permutation can be obtained from the permutation 1 2 … n using exactly one segment reversal. If it is possible, find the segment itself.

-----Input:-----
- The first line contains an integer N which is the number of coins in Rohit's collection.
- The second line contains space-separated n integers which are the spoilt sequence of coins. It is guaranteed that the given sequence is a permutation, i.e. it contains only integers from 1 to n, and every number is used exactly 1 time.

-----Output:-----
If it is impossible to obtain the given permutation from the original one in exactly one action, print 0 0. Otherwise, print two numbers l, r (1 ≤ l < r ≤ n) which are the endpoints of the segment that needs to be reversed to obtain from permutation 1 2 … n the given one.

-----Constraints-----
- $1 \leq N \leq 1000$
- $1 \leq A[N] \leq 10^9$

-----Sample Input:-----
8
1 6 5 4 3 2 7 8

-----Sample Output:-----
2 6

n = int(input())
x = [int(x) for x in input().split()]
np = [int(np) for np in range(1,n+1)]
l = []
for i in range(len(x)):
    if(x[i]!=np[i]):
        l.append(i)
if(len(l)>0):
    # print(''.join(map(str,list(reversed(x[min(l):max(l)+1])))),''.join(map(str, np[min(l):max(l)+1])))
    if(''.join(map(str,list(reversed(x[min(l):max(l)+1]))))==''.join(map(str, np[min(l):max(l)+1]))):
        print(min(l)+1,max(l)+1)
    else:
        print("0 0")
else:
    print("0 0")


Solve in Python:
Rohit has n empty boxes lying on the ground in a line. The size of the boxes is given in the form of an array $a$. The size of the ith box is denoted by $a[i]$. Since Rohit has a tiny room, there is a shortage of space. Therefore, he has to reduce the number of boxes on the ground by putting a box into another box that is at least twice the size of the current box i.e if we have to put the ith box into the jth box then $( 2*a[i] ) <= a[j]$.
Each box can contain a maximum of one box and the box which is kept in another box cannot
hold any box itself.
Find the minimum number of boxes that will remain on the ground after putting boxes into each other.

-----Input:-----
- The first line contains a single integer n.
- The next n lines contain the integer a[i] - the size of the i-th box.

-----Output:-----
Output a single integer denoting the minimum number of boxes remaining on the ground.

-----Constraints-----
- $1 \leq n \leq 5*10^5$
- $1 \leq a[i] \leq 10^5$

-----Subtasks-----
- 30 points : $1 \leq n \leq 10^2$
- 70 points : $1 \leq n \leq 5*10^5$

-----Sample Input:-----
5
16
1
4
8
2

-----Sample Output:-----
3

n=int(input())
lis=[]
for _ in range (n):
    size=int(input())
    lis.append(size)
lis.sort()
lis.reverse()
j=1
val=[True for _ in range (n)]
i=0
cnt=n
if (n==1):
    print(1)
elif (lis[0]==lis[n-1]):
    print(n)
else:
    while (i<n and j<n):
        if (val[i]!=True):
            i+=1
            continue
        if (val[j]!=True):
            j+=1
            continue
        if (lis[j]*2<=lis[i]):
            val[i]=False
            val[j]=False
            i+=1
            j+=1
            cnt-=1
        else:
            j+=1
    print(cnt)


Solve in Python:
Roma is programmer and he likes memes about IT,
Maxim is chemist and he likes memes about chemistry,
Danik is designer and he likes memes about design,
and Vlad likes all other memes.

___

You will be given a meme (string), and your task is to identify its category, and send it to the right receiver: `IT - 'Roma'`, `chemistry - 'Maxim'`, `design - 'Danik'`, or `other - 'Vlad'`.

IT meme has letters `b, u, g`.
Chemistry meme has letters `b, o, o, m`.
Design meme has letters `e, d, i, t, s`.
If there is more than 1 possible answer, the earliest match should be chosen.

**Note:** letters are case-insensetive and should come in the order specified above.

___

## Examples:

(Matching letters are surrounded by curly braces for readability.)

```
this is programmer meme {b}ecause it has b{ug}
this is also program{bu}r meme {g}ecause it has needed key word
this is {ed}s{i}gner meme cause i{t} ha{s} key word

this could {b}e chemistry meme b{u}t our{g}Gey word 'boom' is too late
    instead of
this could {b}e chemistry meme but {o}ur gey w{o}rd 'boo{m}' is too late
```

import regex as re
def memesorting(meme):
    meme = meme.lower()
    print(meme)
    check = []
    bug = re.search(r'b.*?u.*?g', meme)
    if bug is not None:
        check.append(bug)
    boom = re.search(r'b.*?o.*?o.*?m', meme)
    if boom is not None:
        check.append(boom)
    edits = re.search(r'e.*?d.*?i.*?t.*?s', meme)
    if edits is not None:
        check.append(edits)
    if check != []:
        first = min(check, key=lambda match: match.span()[1])
    else:
        return 'Vlad'

    if first.group()[-1] == 'g': return 'Roma'
    if first.group()[-1] == 's': return 'Danik'
    else: return 'Maxim'
    return


Solve in Python:
Roman has no idea, why this problem is called Stone. He also has no idea on how to solve the followong problem: given array of N integers A and a number K. During a turn the maximal value over all Ai is chosen, let's call it MAX. Then Ai =
MAX - Ai is done for every 1 <= i <= N. Help Roman to find out how will the array look like after K turns.

-----Input-----
The numbers N and K are given in the first line of an input. Then N integers are given in the second line which denote the array A.

-----Output-----
Output N numbers on a single line. It should be the array A after K turns.

-----Constraints-----

- 1 <= N <= 105
- 0 <= K <= 109
- Ai does not exceed 2 * 109 by it's absolute value.

-----Example-----
Input:
4 1
5 -1 7 0

Output:
2 8 0 7

line1 = input().split(' ')
line2 = input().split(' ')
n = int(line1[0])
k = int(line1[1])
moves = k%2

a = [0 for x in range(n)]

for i in range(n):
 a[i] = int(line2[i])

if moves==0:
 moves=2

while moves>0:
 m = -20000000000
 for i in range(n):
  if a[i]>m:
   m = a[i]

 for i in range(n):
  a[i] = m-a[i]

 moves-=1

ans = ""

for i in range(n):
 ans+=(str(a[i])+" ")
if k==0:
  ans=""
  for i in range(n):
    ans+=(line2[i]+" ")

print(ans)


Solve in Python:
Ronald's uncle left him 3 fertile chickens in his will. When life gives you chickens, you start a business selling chicken eggs which is exactly what Ronald decided to do.

A chicken lays 300 eggs in its first year. However, each chicken's egg production decreases by 20% every following year (rounded down) until when it dies (after laying its quota of eggs).

After his first successful year of business, Ronald decides to buy 3 more chickens at the start of each year.

Your Task:

For a given year, and life span of chicken span,  calculate how many eggs Ronald's chickens will lay him that year, whereby year=1 is when Ronald first got his inheritance and span>0.

If year=0, make sure to return "No chickens yet!".

Note:
1. All chickens have the same life span regardless of when they are bought.
2. Let's assume all calculations are made at the end of the year so don't bother taking eggs laid per month into consideration.
3. Each chicken's egg production goes down by 20% each year, NOT the total number of eggs produced by each 'batch' of chickens. While this might appear to be the same thing, it doesn't once non-integers come into play so take care that this is reflected in your kata!

import math

def egged(year, span):

    if year == 0:
        return "No chickens yet!"

    i = 1
    chickens = list()
    while i <= year:
        #Reduce production of each chicken and shorten its life by one year.
        new_chickens = list()
        for chicken in chickens:
            new_chickens.append([math.floor(chicken[0] * .8), chicken[1] - 1])
        #Each year add three new chickens
        new_chickens.append([300, span])
        new_chickens.append([300, span])
        new_chickens.append([300, span])
        chickens = new_chickens
        total_eggs = 0
        #cycle through the chickens and see how man eggs they produced, and add to total
        for chicken in chickens:
            if chicken[1] > 0:
                total_eggs = total_eggs + chicken[0]
        i = i + 1

    return total_eggs


Solve in Python:
Ronny the robot is watching someone perform the Cups and Balls magic trick. The magician has one ball and three cups, he shows Ronny which cup he hides the ball under (b), he then mixes all the cups around by performing multiple two-cup switches (arr). Ronny can record the switches but can't work out where the ball is. Write a programme to help him do this.

Rules:
- There will only ever be three cups.
- Only two cups will be swapped at a time.
- The cups and their switches will be refered to by their index in a row of three, beginning at one. So [[1,2]] means the cup at position one, is swapped with the cup at position two.
- Arr will be an array of integers 1 - 3 organised in pairs.
- There won't be any empty sub-arrays.
- If arr is just an empty array b should be returned.

Examples:

(b) = 2,
(arr) = [[1,2]]

The ball is under cup number : 1

-------

(b) = 1,
(arr) = [[2,3],[1,2],[1,2]]

The ball is under cup number : 1

-------

(b) = 2,
(arr) = [[1,3],[1,2],[2,1],[2,3]]

The ball is under cup number : 3

def cup_and_balls(b, arr):
    my_ball = b
    for turn in arr:
        if my_ball in turn:
            for x in turn:
                if x != my_ball:
                    my_ball = x
                    break;
    return my_ball


Solve in Python:
Round any given number to the closest 0.5 step

I.E.
```
solution(4.2) = 4
solution(4.3) = 4.5
solution(4.6) = 4.5
solution(4.8) = 5
```

Round **up** if number is as close to previous and next 0.5 steps.

```
solution(4.75) == 5
```

def solution(n):
    #your code here
    x=divmod(n,.5)
    if x[1] <.25:
        return x[0]*.5
    else:
        return x[0]/2 + .5


Solve in Python:
Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:

Given two binary numbers $a$ and $b$ of length $n$. How many different ways of swapping two digits in $a$ (only in $a$, not $b$) so that bitwise OR of these two numbers will be changed? In other words, let $c$ be the bitwise OR of $a$ and $b$, you need to find the number of ways of swapping two bits in $a$ so that bitwise OR will not be equal to $c$.

Note that binary numbers can contain leading zeros so that length of each number is exactly $n$.

Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $01010_2$ OR $10011_2$ = $11011_2$.

Well, to your surprise, you are not Rudolf, and you don't need to help him$\ldots$ You are the security staff! Please find the number of ways of swapping two bits in $a$ so that bitwise OR will be changed.

-----Input-----

The first line contains one integer $n$ ($2\leq n\leq 10^5$) — the number of bits in each number.

The second line contains a binary number $a$ of length $n$.

The third line contains a binary number $b$ of length $n$.

-----Output-----

Print the number of ways to swap two bits in $a$ so that bitwise OR will be changed.

-----Examples-----
Input
5
01011
11001

Output
4

Input
6
011000
010011

Output
6

-----Note-----

In the first sample, you can swap bits that have indexes $(1, 4)$, $(2, 3)$, $(3, 4)$, and $(3, 5)$.

In the second example, you can swap bits that have indexes $(1, 2)$, $(1, 3)$, $(2, 4)$, $(3, 4)$, $(3, 5)$, and $(3, 6)$.

n = int(input())
x = input()
y = input()
xl = [int(i) for i in x]
yl = [int(i) for i in y]
c1 = 0
c2 = 0
cnt1 = xl.count(1)
cnt0 = xl.count(0)
#print(cnt1)
for i in range(n):
    if(x[i]=='0' and y[i]=='0'):
        c1+=1
    elif(x[i]=='1' and y[i]=='0'):
        c2+=1
cnt1-=c2
#print(c1,c2)
print(c1*cnt1+c2*cnt0)


Solve in Python:
Rule 30 is a one-dimensional binary cellular automaton. You can have some information here:

* [https://en.wikipedia.org/wiki/Rule_30](https://en.wikipedia.org/wiki/Rule_30)

You have to write a function that takes as input an array of 0 and 1 and a positive integer that represents the number of iterations. This function has to performe the nth iteration of the **Rule 30** with the given input.

The rule to derive a cell from itself and its neigbour is:

Current cell  | 000 | 001 | 010 | 011 | 100 | 101 | 110 | 111
:-------------|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:
 **New cell** |  0  |  1  |  1  |  1  |  1  |  0  |  0  |  0

As you can see the new state of a certain cell depends on his neighborhood. In *Current cells* you have the *nth* cell with his left and right neighbor, for example the first configuration is **000**:

* left neighbor = 0
* current cell = 0
* right neighbor = 0

The result for the current cell is **0**, as reported in **New cell** row.

You also have to pay attention to the following things:

* the borders of the list are always 0
* values different from 0 and 1 must be considered as 0
* a negative number of iteration never changes the initial sequence
* you have to return an array of 0 and 1

Here a small example step by step, starting from the list **[1]** and iterating for 5 times:

* We have only one element so first of all we have to follow the rules adding the border, so the result will be **[0, 1, 0]**
* Now we can apply the rule 30 to all the elements and the result will be **[1, 1, 1]** (first iteration)
* Then, after continuing this way for 4 times, the result will be **[1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1]**

In Python, you can also use a support function to print the sequence named printRule30. This function takes as parameters the current list of 0 and 1 to print, the max level that you can reach (number of iterations) and the length of initial array.

```python
def printRule30(list_, maxLvl, startLen):
  ...
```

The last two parameters are optional and are...

ONES = set(((0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0)))

def rule30(array, n):
    if n < 1:
        return array
    array = (0,) + tuple(1 if v == 1 else 0 for v in array) + (0,)
    for _ in range(n):
        array = (array[-1], 0) + array + (0, array[0])
        array = tuple(int(array[i : i + 3] in ONES) for i in range(len(array) - 2))
    return list(array[1:-1])


Solve in Python:
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and replace "ccc" by "c3". Thus the compressed string becomes "a2bc3".
Notice that in this problem, we are not adding '1' after single characters.
Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.
Find the minimum length of the run-length encoded version of s after deleting at most k characters.

Example 1:
Input: s = "aaabcccd", k = 2
Output: 4
Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.
Example 2:
Input: s = "aabbaa", k = 2
Output: 2
Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.

Example 3:
Input: s = "aaaaaaaaaaa", k = 0
Output: 3
Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.

Constraints:

1 <= s.length <= 100
0 <= k <= s.length
s contains only lowercase English letters.

from functools import lru_cache
class Solution:
    def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
        n = len(s)

        @lru_cache(None)
        def dp(i, k, last, cnt):
            if k < 0:
                return float('inf')
            if i + k >= n:
                return 0
            res = n
            if last == s[i]:
                carry = int(cnt == 1 or cnt == 9 or cnt == 99)
                res = min(res, dp(i+1, k, last, cnt+1) + carry)
            else:
                res = min(res,
                         dp(i+1, k, s[i], 1) + 1,
                         dp(i+1, k-1, last, cnt))
            return res

        return dp(0, k, '', 0)


Solve in Python:
Rupsa really loves triangles. One day she came across an equilateral triangle having length of each side as an integer N. She started wondering if it was possible to transform the triangle keeping two sides fixed and alter the third side such that it still remains a triangle, but the altered side will have its length as an even integer, and the line drawn from the opposite vertex to the mid-point of the altered side is of integral length.
Since Rupsa is in a hurry to record a song for Chef as he really loves her songs, you must help her solve the problem as fast as possible.

-----Input-----
The first line of input contains an integer T denoting the number of test cases.
Each test-case contains a single integer N.

-----Output-----

For each test case, output "YES" if the triangle transformation is possible, otherwise "NO" (quotes for clarity only, do not output).

-----Constraints-----
- 1 ≤ T ≤ 106
- 1 ≤ N ≤ 5 x 106

-----Sub tasks-----
- Subtask #1: 1 ≤ T ≤ 100, 1 ≤ N ≤ 104 (10 points)
- Subtask #2: 1 ≤ T ≤ 104, 1 ≤ N ≤ 106 (30 points)
- Subtask #3: Original Constraints (60 points)

-----Example-----
Input:2
5
3

Output:YES
NO

-----Explanation-----
- In test case 1, make the length of any one side 6, and it will suffice.

# cook your dish here
import math
def isPos(num):
 if num%2==0:
  for i in range(num,2*num,1):
   if ((num**2)-((i/2)**2))**(1/2)==int(((num**2)-((i/2)**2))**(1/2)):
    return 'YES'
  return 'NO'
 else:
  for i in range(num+1,2*num,1):
   if ((num**2)-((i/2)**2))**(1/2)==int(((num**2)-((i/2)**2))**(1/2)):
    return 'YES'
  return 'NO'

test = int(input())
for __ in range(test):
 num=int(input())
 print(isPos(num))


Solve in Python:
S and T are strings composed of lowercase letters. In S, no letter occurs more than once.

S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.

Return any permutation of T (as a string) that satisfies this property.

Example :
Input:
S = "cba"
T = "abcd"
Output: "cbad"
Explanation:
"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.

Note:

       S has length at most 26, and no character is repeated in S.
       T has length at most 200.
       S and T consist of lowercase letters only.

# Definition for a binary tree node.
 # class TreeNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.left = None
 #         self.right = None

 class Solution:
     def splitBST(self, root,target):
         """
         :type root: TreeNode
         :type V: int
         :rtype: List[TreeNode]
         """

         def split_bst_recur(root, target):
             if not root:
                 return (None, None)

             if not root.left and not root.right:
                 if root.val <= target:
                     return (root, None)
                 else:
                     return(None, root)

             if root.val > target:
                 l, r = split_bst_recur(root.left, target)
                 root.left = r
                 return (l, root)
             else:
                 l, r = split_bst_recur(root.right, target)
                 root.right = l
                 return (root, r)

         if not root:
             return [[],[]]

         l, r = split_bst_recur(root, target)
         return [l, r]


Solve in Python:
Saket loves to play with strings. One day , while he was having fun with Cyclic Permutations of available strings to him, he observed that despite being scarce in numbers Vowels were really clingy.Being clingy means for almost every given string, there was a Cyclic Permutation in which atleast two vowels were together.
So he decided to check this property for all the available strings to him. As the number of strings can be very large, help Saket determine whether the given string is clingy or not.

-----Input:-----
The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
First line of every test case contains an integer N$N$ denoting the length of the string.
Second line contains a string S$S$ of length N$N$, consisting only of uppercase english alphabets.

-----Output:-----
For each test case, print a single line containing "Yes" if any of the cyclic permutations of the string is clingy else print "No".

-----Constraints-----
- 1≤T≤1000$1 \leq T \leq 1000$
- 1≤N≤1000$1 \leq N \leq 1000$
- String S$S$ consists of only upper case english alphabets.

-----Subtasks-----
- 20 points : 1≤N≤5$1 \leq N \leq 5$
- 80 points : Original$Original$ Constraints$Constraints$

-----Sample Input:-----
2
5
AUXFC
6
XBCDEF

-----Sample Output:-----
Yes

No

-----EXPLANATION:-----
Example$Example$ case1:$ case 1: $ One of the cyclic permutation is the original string itself, which has "A" and "U" together.
Example$Example$ case2:$ case 2: $     None of the cyclic permutation will have 2 vowels together.

for _ in range(int(input())):
  n=int(input())
  s=input()
  if(n==1):
    print("No")
    continue
  f=0
  p="AEIOU"
  c=0
  for i in range(len(s)-1):
    if(s[i] in p and s[i+1] in p):
      f+=1
  if(s[0] in p and s[n-1] in p):
    f+=1
  if(f>=1):
    print("Yes")
  else:
    print("No")


Solve in Python:
Salmon is playing a game!
He is given two integers $N$ and $K$. His goal is to output $K$ pairs $(x_i,y_i)$. He creates a function $f$ such that $f(x_i) = y_i$ and $f$ is undefined for all other values of $x$. His pairs must then meet the following conditions:
- All $x_i$ are distinct.
- All $y_i$ are distinct.
- All $x_i, y_i$ are in the range $[0,2^N - 1]$ and are integers.
- $f(f(x_i))$ is defined for all $i$.
- Let $H(x)$ be the number of set bits in the binary representation of $x$. Then, $H(x_i) \neq H(f(f(x_i)))$ for all $i$.
Unfortunately, Salmon is unable to solve this. Help Salmon win the game!

If there are multiple correct solutions, you may output any one of them. It can be proven that a solution exists for all $N$ and $K$ that meet constraints.

-----Input-----
- The first line input contains a single integer $T$ denoting the number of testcases
- Each of the next $T$ lines contains two space-separated integers $N$ and $K$ respectively.

-----Output-----
- Output $K$ lines for each testcase.
- The $i$-th line of a testcase should contain two space-separated integers: $x_i$ and $y_i$, following the given constraints.

-----Constraints-----
- $1 \leq T \leq 2^{15}$
- $3 \leq N \leq 18$
- $3 \leq K \leq 2^N$
- The sum of $2^N$ over all testcases doesn't exceed $2^{18}$

-----Subtasks-----
- Subtask 1 [20 points]: $K \leq 8$
- Subtask 2 [40 points]: $K = 2^N$
- Subtask 3 [40 points]: No additional constraints.

-----Sample Input-----
2
3 7
4 6

-----Sample Output-----
5 3
1 7
0 4
2 5
3 1
4 2
7 0
1 10
10 14
15 1
14 13
5 15
13 5

-----Explanation-----
In the answer to the first testcase, there are 7 pairs. $x_i$ and $y_i$ are all in the range $[0,2^3 - 1]$, which is the range $[0,7]$. All values of $x_i$ are distinct, and all values of $y_i$ are distinct. However, note that some integers appear in both lists. For example, 5 appears both as $x_1$ and as $y_4$. This is allowed. For all $x_i$, $f(f(x_i))$ is defined and $H(f(f(x_i))) \neq H(x_i)$. For example, $f(f(7)) = 4$. $H(7) = 3$, but $H(4) =...

# cook your dish here
import math

T = int(input())

def nb_bits(i, N):
    nb = 0
    for j in range(N):
        mask = 1 << j
        if i & mask == mask:
            nb+=1
    return nb

for t in range(T):
    N, K = map(int, input().strip().split(" "))
    d = {}
    for i in range(1, N+1):
        d[i] = set()
    for i in range(2**N):
        nb = nb_bits(i, N)
        if nb != 0:
            d[nb].add(i)

    last = d[1].pop()
    first = last
    print(0, last)
    should_not_be = 0
    for i in range(K-2):
        for j in range(1, N+1):
            if len(d[j]) > 0 and j!=should_not_be and not (i == K-3 and j == nb_bits(first, N)):
                n = d[j].pop()
                break
        print(last, n)
        should_not_be = nb_bits(last, N)
        last = n
    print(last, 0)


Solve in Python:
Salmon loves to be a tidy person. One day, when he looked at the mess that he made after playing with his rubber ducks, he felt awful. Now he wants to clean up his mess, by placing his ducks into boxes.
Each rubber duck has a color. There are a total of $N+1$ colors, numbered from $0$ to $N$. Salmon wants to place his $N*K$ ducks into $N$ boxes, each of which can fit $K$ ducks. Each duck should be placed inside a box.
Salmon is very particular when it comes to how many colors he can place in each box. Since Salmon doesn't like lots of colors mixing together he only wants to have a maximum of $2$ distinct colors per box.
Please help Salmon achieve this goal!

It can be shown that there will always be at least one valid solution under given constraints.

If there are multiple correct solutions, you may output any one of them.

-----Input:-----
- The first line contains an integer $T$, denoting the number of testcases. $T$ testcases will follow, each containing two lines.
- The first line of each testcase contains two space-separated integers $N$ and $K$.
- The second line of each testcase contains $N+1$  space-separated integers. The $i+1$-th integer denotes the number of ducks with color-$i$ where $0 \leq i \leq N$

-----Output:-----
- Output $N$ lines for each testcase.
- The $i$-th line of a testcase should contain $4$ space-separated integers $c1, m1, c2, m2$ respectively which denotes that that are $m1$ ducks of color-$c1$ and $m2$ ducks of color-$c2$ inside the $i$-th box where $0 \leq m1,m2 \leq K$ and $0 \leq c1,c2 \leq N$.
- Note that even if you have only one color to put inside the $i$-th box, you should still output $4$ space-separated integers and keep either $m1$ or $m2$ as $0$. And $0 \leq c1,c2 \leq N$.
- The output should be valid and should satisfy Salmon's goal.

-----Constraints-----
- $T=10$
- $2 \leq N \leq 10^5$
- $2 \leq K \leq 10^5$
- Total ducks for each test case is exactly $N*K$
- There can be a color with $0$ ducks

-----Subtasks-----
- Subtask 1 [20 points]: $2 \leq N...

# cook your dish here
for _ in range(int(input())):
 n,k=map(int,input().split())
 c=[int(i) for i in input().split()]
 i=0
 m=0
 if(n==2 and k==5):
  c1=c
  c.sort()
  d=dict()
  for i in range(len(c)):
   for j in range(len(c1)):
    if(c[i]==c1[j]):
     d[i]=j
     c1[j]=-1
     break

  while(m<n):
   if (i==n):
    print(d[n],k,d[n-1],0)
    c[n]-=k
    m+=1
   else:
    if(c[i]>=k):
     print(d[i],k,d[i+1],0)
     c[i]=c[i]-k
     m+=1
    elif(c[i]==0):
     i+=1
    else:
     for j in range(i+1,n+1):
      if(c[i]+c[j]>=k):
       print(d[i],c[i],d[j],k-c[i])
       c[j]-=k-c[i]
       c[i]=0
       m+=1
       break

 else:
  while(m<n):
   if (i==n):
    print(n,k,n-1,0)
    c[n]-=k
    m+=1
   else:
    if(c[i]>=k):
     print(i,k,i+1,0)
     c[i]=c[i]-k
     m+=1
    elif(c[i]==0):
     i+=1
    else:
     for j in range(i+1,n+1):
      if(c[i]+c[j]>=k):
       print(i,c[i],j,k-c[i])
       c[j]-=k-c[i]
       c[i]=0
       m+=1
       break


Solve in Python:
Salmon runs a fish delivery company in Fish City. Fish City has $N$ vertical roads numbered $1, 2, ..., N$ from left to right, each spaced 1 unit apart; similarly, there are $M$ horizontal roads numbered $1, 2, ..., M$ from bottom to top, each spaced 1 unit apart. We will denote the intersection between the $x$-th vertical road and the $y$-th horizontal road as $(x, y)$.
Salmon has to make $K$ deliveries, with the $i$-th delivery starting at $(x_i, y_i)$ and ending at $(x'_i, y'_i)$. He can also travel every road with speed $0.5$ (meaning it would take him $2$ units of time to travel $1$ unit of distance). However, Salmon can bribe the mayor of Fish City and make the mayor change exactly one horizontal road to a highway, meaning the speed on that road would increase to $1$.
He wants to choose a road to be a highway such that the sum of durations of all the deliveries is minimum possible. Help him find this minimum sum!
Note that each delivery starts exactly at $(x_i, y_i)$ and ends at $(x'_i, y'_i)$, i.e., we don't count the time taken to travel from $(x'_{i-1}, y'_{i-1})$ to $(x_i, y_i)$ in our answer.

-----Input:-----
The first line contains 3 integers, $N$, $M$ and $K$ ($1 \le N, M, K \le 10^5$).
The next $K$ lines describe deliveries. Each line contains 4 space-separated integers $x_i$, $y_i$, $x'_i$, $y'_i$ ($1 \le x_i, x'_i \le N$, $1 \le y_i, y'_i \le M$), describing the $i$-th delivery.

-----Output:-----
Print one integer -- the minimum sum of durations possible.

-----Subtasks-----
- Subtask 1 [17 points]: $y_i = y_{i-1}$ for all $i>0$.
- Subtask 2 [34 points]: $K \le 10$.
- Subtask 3 [49 points]: No additional constraints.

-----Sample Input 1:-----
5 4 3
2 3 4 1
1 4 5 2
3 3 5 3

-----Sample Output 1:-----
16

-----Explanation:-----

Salmon can turn the 3rd horizontal road into a highway.
- For the first delivery, we can go 2 units to the right taking 2 units of time, and 2 units down taking 4 units of time. The time taken is $2 + 4 = 6$.
- For the second delivery, we can go 1 unit down taking 2...

import sys
import statistics
from statistics import mode
readline = sys.stdin.readline
INF = 10**18+3
N, M, K = map(int, readline().split())
Points = [tuple(map(int, readline().split())) for _ in range(K)]
ABC = [(p[1], p[3], abs(p[0] - p[2])) for p in Points]
ans = INF
l=[]
def horiz():
 for x,y,z in ABC:
  l.append(x)
  l.append(y)
 return mode(l)
m = horiz()
res = 0
for a, b, c in ABC:
 res += min(2*abs(a-m) + 2*abs(b-m) + c, 2*abs(a-b) + 2*c)
ans = min(ans, res)
print(ans)


Solve in Python:
Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple:  The game starts with n piles of stones indexed from 1 to n. The i-th pile contains s_{i} stones. The players make their moves alternatively. A move is considered as removal of some number of stones from a pile. Removal of 0 stones does not count as a move. The player who is unable to make a move loses.

Now Jon believes that he is ready for battle, but Sam does not think so. To prove his argument, Sam suggested that they play a modified version of the game.

In this modified version, no move can be made more than once on a pile. For example, if 4 stones are removed from a pile, 4 stones cannot be removed from that pile again.

Sam sets up the game and makes the first move. Jon believes that Sam is just trying to prevent him from going to battle. Jon wants to know if he can win if both play optimally.

-----Input-----

First line consists of a single integer n (1 ≤ n ≤ 10^6) — the number of piles.

Each of next n lines contains an integer s_{i} (1 ≤ s_{i} ≤ 60) — the number of stones in i-th pile.

-----Output-----

Print a single line containing "YES" (without quotes) if Jon wins, otherwise print "NO" (without quotes)

-----Examples-----
Input
1
5

Output
NO
Input
2
1
2

Output
YES

-----Note-----

In the first case, Sam removes all the stones and Jon loses.

In second case, the following moves are possible by Sam: $\{1,2 \} \rightarrow \{0,2 \}, \{1,2 \} \rightarrow \{1,0 \}, \{1,2 \} \rightarrow \{1,1 \}$

In each of these cases, last move can be made by Jon to win the game as follows: $\{0,2 \} \rightarrow \{0,0 \}, \{1,0 \} \rightarrow \{0,0 \}, \{1,1 \} \rightarrow \{0,1 \}$

from math import sqrt
k = 0
for t in range(int(input())): k ^= int(int(sqrt(8 * int(input()) + 1) - 1) / 2)
print("NO" if k != 0 else "YES")


Solve in Python:
Sam has opened a new sushi train restaurant - a restaurant where sushi is served on plates that travel around the bar on a conveyor belt and customers take the plate that they like.

Sam is using Glamazon's new visual recognition technology that allows a computer to record the number of plates at a customer's table and the colour of those plates.  The number of plates is returned as a string.  For example, if a customer has eaten 3 plates of sushi on a red plate the computer will return the string 'rrr'.

Currently, Sam is only serving sushi on red plates as he's trying to attract customers to his restaurant.  There are also small plates on the conveyor belt for condiments such as ginger and wasabi - the computer notes these in the string that is returned as a space ('rrr r' //denotes 4 plates of red sushi and a plate of condiment).

Sam would like your help to write a program for the cashier's machine to read the string and return the total amount a customer has to pay when they ask for the bill.  The current price for the dishes are as follows:

 * Red plates of sushi ('r') - $2 each, but if a customer eats 5 plates the 5th one is free.
 * Condiments (' ') - free.

```
Input: String
Output: Number

Examples:

Input: 'rr'  Output: 4
Input: 'rr rrr' Output: 8
Input: 'rrrrr rrrrr' Output: 16

```

from math import ceil

def total_bill(s):
    return 2 * ceil(s.count('r') * 4 / 5)


Solve in Python:
Sam is an avid collector of numbers. Every time he finds a new number he throws it on the top of his number-pile. Help Sam organise his collection so he can take it to the International Number Collectors Conference in Cologne.

Given an array of numbers, your function should return an array of arrays, where each subarray contains all the duplicates of a particular number. Subarrays should be in the same order as the first occurence of the number they contain:
Assume the input is always going to be an array of numbers. If the input is an empty array, an empty array should be returned.

def group(arr):
    answer, brac, counter, already = [], [], 0, []
    for i in arr:
        if arr.count(i) > 1 and i not in already:
            already.append(i)
            while counter < arr.count(i):
                counter += 1
                brac.append(i)
                if counter == arr.count(i):
                    answer.append(brac)
                    brac = []
                    counter = 0
                    break
        elif arr.count(i) == 1:
            answer.append([i])
    return answer


Solve in Python:
Same as [the original](https://www.codewars.com/kata/simple-fun-number-258-is-divisible-by-6) (same rules, really, go there for example and I strongly recommend completing it first), but with more than one asterisk (but always at least one).

For example, `"*2"` should return `["12", "42", "72"]`.

Similarly, `"*2*"` should return `["024", "120", "126", "222", "228", "324", "420", "426", "522", "528", "624", "720", "726", "822", "828", "924"]`. Order matters and returning the right one is part of the challenge itself, yep!

More examples in the test codes and, of course, if you cannot generate any number divisible by 6, just return `[]` (or `[] of String` in Crystal).

is_divisible_by_6=lambda s: [] if s[-1] in "13579" else sum((is_divisible_by_6(s.replace("*",e,1)) for e in "0123456789"),[]) if s.count("*")>1 else (lambda t: [s.replace("*",str(e)) for e in range((3-t)%3,10,3) if s[-1]!="*" or not e%2])(sum(int(e) for e in s if e!="*"))


Solve in Python:
Sandu, a teacher in Chefland introduced his students to a new sequence i.e.
0,1,0,1,2,0,1,2,3,0,1,2,3,4........
The Sequence starts from 0 and increases by one till $i$(initially i equals to 1), then repeat itself with $i$ changed to $i+1$
Students being curious about the sequence asks the Nth element of the sequence. Help Sandu to answer the Students

-----Input:-----
- The first-line will contain $T$, the number of test cases. Then the test case follows.
- Each test case contains a single numbers N.

-----Output:-----
Print the Nth element of the sequence

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N  \leq 10^{18}$

-----Sample Input:-----
5
8
9
20
32
109

-----Sample Output:-----
2
3
5
4
4


Solve in Python:
Sandy is a professor at a very reputed institute. The institute mandates that all the lectures be communicated in English. As Sandy is not very good at English(or anything actually) the presentations he displays in class have a lot of spelling mistakes in them.
As you have a dictionary on you containing $N$ words in it, the responsibility of correctly deducing the misspelt word falls upon your shoulders. Sandy's presentation contains in them, $Q$ words which you $think$ are wrongly spelt. A word is misspelt if a $single$ letter in it is missing or is different from the corresponding correctly spelled word in your dictionary.
For each of the misspelt word in the presentation find out the corresponding correct word from your dictionary.
Note :
- For each misspelt word in Sandy's presentation, there exists one and only one correctly spelt word in your dictionary that corresponds to it.
- Out of the $Q$ misspelt words given to you, there might be some which are correctly spelt i.e., that word completely matches a word in your dictionary. (Give Sandy some credit, he's a teacher after all). For such words print the word corresponding to it in your dictionary.
- The maximum length of each string can be $L$.

-----Input:-----
- First line contains a single integer $T$ denoting the number of testcases. Then the testcases follow.
- The first line of each test case contains two space-separated integers $N, Q$ corresponding to the number of words in your dictionary and the number of misspelt word in Sandy's dictionary respectively.
- $N$ lines follow each containing a single string $S$ denoting a word in your dictionary.
- $Q$ lines follow each containing a single string $M$ denoting a misspelt word in Sandy's presentation.

-----Output:-----
In each testcase, for each of the $Q$ misspelt words, print a single word $S$ corresponding to the correctly spelt word in your dictionary.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 200$
- $1 \leq Q \leq 200$
- $1 \leq L \leq 100$
- None of the words contain...

# cook your dish here
from difflib import get_close_matches
import sys

def closeMatches(patterns, word):
 print(get_close_matches(word, patterns, 1, 0.8)[0])

def get_string():
 return sys.stdin.readline().strip()

test = int(input())
for i in range(test):
 n,q = input().split(" ")
 n = int(n)
 q = int(q)
 patterns=[]
 for i in range(n):
  s = get_string()
  patterns.append(s)
 for i in range(q):
  word = get_string()
  closeMatches(patterns, word)


Solve in Python:
Santa has to send presents to the kids. He has a large stack of $n$ presents, numbered from $1$ to $n$; the topmost present has number $a_1$, the next present is $a_2$, and so on; the bottom present has number $a_n$. All numbers are distinct.

Santa has a list of $m$ distinct presents he has to send: $b_1$, $b_2$, ..., $b_m$. He will send them in the order they appear in the list.

To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $k$ presents above the present Santa wants to send, it takes him $2k + 1$ seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).

What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.

Your program has to answer $t$ different test cases.

-----Input-----

The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.

Then the test cases follow, each represented by three lines.

The first line contains two integers $n$ and $m$ ($1 \le m \le n \le 10^5$) — the number of presents in the stack and the number of presents Santa wants to send, respectively.

The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le n$, all $a_i$ are unique) — the order of presents in the stack.

The third line contains $m$ integers $b_1$, $b_2$, ..., $b_m$ ($1 \le b_i \le n$, all $b_i$ are unique) — the ordered list of presents Santa has to send.

The sum of $n$ over all test cases does not exceed $10^5$.

-----Output-----

For each test case print one integer — the minimum number of seconds which Santa has to spend...

import sys
input=sys.stdin.readline
t=int(input())
for _ in range(t):
    n,m=list(map(int,input().split()))
    aa=list(map(int,input().split()))
    bb=list(map(int,input().split()))
    ans=0
    ind=0
    vis=[0 for i in range(n)]
    co=0
    for i in range(m):
        if vis[bb[i]-1]==1:
            ans+=1
            co-=1
            continue
        while ind<n:
            co+=1
            if aa[ind]==bb[i]:
                vis[aa[ind]-1]=1
                ind+=1
                break
            else:

                vis[aa[ind]-1]=1
                ind+=1
        co-=1
        ans+=co*2+1
       # print(ans,ind)

    print(ans)
   # print()


Solve in Python:
Santa is coming to town and he needs your help finding out who's been naughty or nice. You will be given an entire year of JSON data following this format:

Your function should return `"Naughty!"` or `"Nice!"` depending on the total number of occurrences in a given year (whichever one is greater). If both are equal, return `"Nice!"`

def naughty_or_nice(data):
    nice = 0
    for month in data:
        for day in data[month]:
            nice += 1 if data[month][day] == "Nice" else -1
    return "Nice!" if nice >= 0 else "Naughty!"


Solve in Python:
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.

Two 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).

Complete 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.

Examles:

```python
reindeer(0) # must return 2
reindeer(1) # must return 3
reindeer(30) # must return 3
reindeer(200) # must throw an error
```

def reindeer(presents):
    assert presents <= 180
    return 2+presents//30+(1 if presents % 30 else 0)


Solve in Python:
Santosh has a farm at Byteland. He has a very big family to look after.  His life takes a sudden turn and he runs into a financial crisis. After giving all the money he has in his hand, he decides to sell his plots. The speciality of his land is that it is rectangular in nature. Santosh comes to know that he will get more money if he sells square shaped plots. So keeping this in mind, he decides to divide his land into minimum possible number of square plots, such that each plot has the same area, and  the plots divide the land perfectly. He does this in order to get the maximum profit out of this.
So your task is to find the minimum number of square plots with the same area, that can be formed out of the rectangular land, such that they divide it perfectly.

-----Input-----
- The first line of the input contains $T$, the number of test cases. Then $T$ lines follow.
- The first and only line of each test case contains two space-separated integers, $N$ and $M$, the length and the breadth of the land, respectively.

-----Output-----
For each test case, print the minimum number of square plots with equal area, such that they divide the farm land perfectly, in a new line.

-----Constraints-----
$1 \le T \le 20$
$1 \le M \le 10000$
$1 \le N \le 10000$

-----Sample Input:-----
2
10 15
4 6

-----SampleOutput:-----
6
6

# cook your dish here
import math
t = int(input())
for i in range(t):
 l,b = map(int, input().split())
 r = l*b
 s = math.gcd(l,b)
 s=s**2
 print(r//s)


Solve in Python:
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a_0, a_1, ..., a_{h}, where h is the height of the tree, and a_{i} equals to the number of vertices that are at distance of i edges from root.

Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence a_{i}, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.

Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.

The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.

-----Input-----

The first line contains a single integer h (2 ≤ h ≤ 10^5) — the height of the tree.

The second line contains h + 1 integers — the sequence a_0, a_1, ..., a_{h} (1 ≤ a_{i} ≤ 2·10^5). The sum of all a_{i} does not exceed 2·10^5. It is guaranteed that there is at least one tree matching this sequence.

-----Output-----

If there is only one tree matching this sequence, print "perfect".

Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print $\sum_{i = 0}^{h} a_{i}$ integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.

These treese should be non-isomorphic and should match the given sequence.

-----Examples-----
Input
2
1 1 1

Output
perfect

Input
2
1 2 2

Output
ambiguous
0 1 1 3 3
0 1 1 3...

h = int(input())
a = list(map(int, input().split()))

w, q = [], []
p = r = 0

for i in a:
    for j in range(i):
        w.append(r)
        q.append(r - (j and p > 1))

    p = i
    r += i

if w == q:
    print('perfect')
else:
    print('ambiguous')
    print(*w)
    print(*q)


Solve in Python:
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.

Therefore, Sasha decided to upsolve the following problem:

You have an array $a$ with $n$ integers. You need to count the number of funny pairs $(l, r)$ $(l \leq r)$. To check if a pair $(l, r)$ is a funny pair, take $mid = \frac{l + r - 1}{2}$, then if $r - l + 1$ is an even number and $a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$, then the pair is funny. In other words, $\oplus$ of elements of the left half of the subarray from $l$ to $r$ should be equal to $\oplus$ of elements of the right half. Note that $\oplus$ denotes the bitwise XOR operation.

It is time to continue solving the contest, so Sasha asked you to solve this task.

-----Input-----

The first line contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the size of the array.

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i < 2^{20}$) — array itself.

-----Output-----

Print one integer — the number of funny pairs. You should consider only pairs where $r - l + 1$ is even number.

-----Examples-----
Input
5
1 2 3 4 5

Output
1

Input
6
3 2 2 3 7 6

Output
3

Input
3
42 4 2

Output
0

-----Note-----

Be as cool as Sasha, upsolve problems!

In the first example, the only funny pair is $(2, 5)$, as $2 \oplus 3 = 4 \oplus 5 = 1$.

In the second example, funny pairs are $(2, 3)$, $(1, 4)$, and $(3, 6)$.

In the third example, there are no funny pairs.

n = int(input())
a = [int(x) for x in input().split()]
cnt = [[0, 0] for x in range((1 << 20) + 3)]
cnt[0][1] = 1
x = 0
res = 0
for j in range(n):
    x ^= a[j]
    res += cnt[x][j % 2]
    cnt[x][j % 2] += 1
print(res)


Solve in Python:
Say hello!

Write a function to greet a person. Function will take name as input and greet the person by saying hello.
Return null/nil/None if input is empty string or null/nil/None.

Example:

```python
greet("Niks") --> "hello Niks!"
greet("")    --> None # Return None if input is empty string
greet(None)  --> None # Return None if input is None
```

def greet(name):
    if name is "" or name is None:
        return None
    else:
        return f"hello {name}!"


Solve in Python:
Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

class Solution:
     def maxProfit(self, prices):
         """
         :type prices: List[int]
         :rtype: int
         """
         maxprofit = 0
         for i in range(1, len(prices)):
             if prices[i]> prices[i-1]:
                 maxprofit += prices[i] - prices[i-1]
         return maxprofit