Solve in Python:
You are given a sequence $A_1, A_2, \ldots, A_N$. You have to split the array into maximum number of non-empty subarrays such that the gcd of elements of each subarray is equal to 1.

-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output:-----
For each test case, print a single line containing one integer ― the maximum number of subarrays formed, or $-1$ if the array cannot be split while satisfying the above condition.

-----Constraints-----
- $1 \le T \le 3$
- $1 \le N \le 5 \cdot 10^5$
- $1 \le A_i \le 10^6$ for each valid $i$

-----Sample Input:-----
2
3
2 2 3
4
2 3 3 2

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

'''input
2
3
2 2 3
4
2 3 3 2
'''
import math

for _ in range(int(input())):
 n = int(input())
 a = list(map(int, input().split()))
 count = 0
 i = 0
 while i < len(a):
  if a[i] == 1:
   count += 1
   i += 1
   continue
  curr_gcd = a[i]
  while i < len(a) and curr_gcd != 1:
   curr_gcd = math.gcd(curr_gcd, a[i])
   if curr_gcd == 1:
    count += 1
    i += 1
    # print(i)
    break
   i += 1
 print(count)


Solve in Python:
You are given a sequence $A_1, A_2, \ldots, A_N$. You may perform the following operation an arbitrary number of times (including zero): choose two adjacent elements of this sequence, i.e. $A_i$, $A_{i+1}$ for some valid $i$, and swap them. However, for each valid $i$, it is not allowed to choose $A_i$ (the element with the index $i$, regardless of its value at any point in time) more than once in total during this process.
Find the maximum of the sum $S = \sum_{i=1}^N A_i \cdot i$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print a single line containing one integer ― the maximum possible value of $S$.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^5$
- $1 \le A_i \le 10^9$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $10^6$

-----Subtasks-----
Subtask #1 (50 points):
- $N \le 20$
- the sum of $N$ over all test cases does not exceed $200$
Subtask #2 (50 points): original constraints

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

-----Example Output-----
30
39

-----Explanation-----
Example case 1: Swap the first and second element of the initial sequence. Then, swap the third and fourth element of the resulting sequence. The final sequence $A$ is $(1, 2, 3, 4)$.
Example case 2: Swap the second and third element to make the sequence $(7, 3, 6, 2)$.

for j in range(int(input())):
 n = int(input())
 x = list(map(int,input().split()))
 aman = [0,x[0]]
 for i in range(2,n+1):
  aman.append(max(aman[i-1]+x[i-1]*i,aman[i-2]+x[i-1]*(i-1)+x[i-2]*(i)))
 print(aman[-1])


Solve in Python:
You are given a sequence $A_1, A_2, \ldots, A_N$. You should select a (not necessarily contiguous) subsequence of $A$ and reverse it. In other words, if you select a subsequence $A_{i_1}, A_{i_2}, \ldots, A_{i_K}$ ($1 \le i_1 < \ldots < i_K \le N$), then for each valid $j$, the $i_j$-th element of the resulting sequence is equal to the $i_{K+1-j}$-th element of the original sequence; all other elements are the same as in the original sequence.
In the resulting sequence, you want to calculate the maximum sum of a contiguous subsequence (possibly an empty sequence, with sum $0$). Find its maximum possible value and a subsequence which you should select in order to obtain this maximum value. If there are multiple solutions, you may find any one of them.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print two lines.
- The first of these lines should contain a single integer ― the maximum possible sum of a contiguous subsequence.
- The second line should contain an integer $K$ followed by a space and $K$ space-separated integers $i_1, i_2, \ldots, i_K$.

-----Constraints-----
- $1 \le T \le 2,000$
- $2 \le N \le 10^5$
- $|A_i| \le 10^9$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $2 \cdot 10^6$

-----Example Input-----
2
5
-4 2 -4 3 -5
3
-3 -2 -1

-----Example Output-----
5
2 2 3
0
0

# cook your dish here
test=int(input())
for _ in range(test):
 n=int(input())
 arr=list(map(int,input().split()))
 pos=0
 num=0
 temp=[]
 for ii in arr:
  if ii>=0:
   pos+=ii
   num+=1
 p=0
 n=0
 for i in range(len(arr)):
  if i<num:
   if arr[i]<0:
    temp.append(i+1)
    n+=1
  else:
   if arr[i]>=0:
    temp.append(i+1)
    p+=1
 print(pos)
 if p==n:
  k=[len(temp)]
  k.extend(temp)
  print(*k)
 else:
  print(0)


Solve in Python:
You are given a sequence $A_1, A_2, \ldots, A_N$. You want all the elements of the sequence to be equal. In order to achieve that, you may perform zero or more moves. In each move, you must choose an index $i$ ($1 \le i \le N$), then choose $j = i-1$ or $j = i+1$ (it is not allowed to choose $j = 0$ or $j = N+1$) and change the value of $A_i$ to $A_j$ — in other words, you should replace the value of one element of the sequence by one of its adjacent elements.
What is the minimum number of moves you need to make in order to make all the elements of the sequence equal?

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print a single line containing one integer — the minimum required number of moves.

-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 100$
- $1 \le A_i \le 100$ for each valid $i$

-----Example Input-----
3
5
1 1 1 1 1
4
9 8 1 8
2
1 9

-----Example Output-----
0
2
1

-----Explanation-----
Example case 1: No moves are needed since all the elements are already equal.
Example case 3: We can perform one move on either $A_1$ or $A_2$.

def changeIt(n,arr):
 m = dict()
 for i in range(n):
  m[arr[i]] = m.get(arr[i],0)+1
 count = 0
 for i in m.keys():
  if m[i] > count:
   count = m[i]
  else:
   continue
 print(len(arr) - count)
 return

#Driver code starts here
t = int(input())
for _ in range(t):
 n = int(input())
 arr = list(map(int,input().split()))
 changeIt(n,arr)


Solve in Python:
You are given a sequence $a_1, a_2, \dots, a_n$, consisting of integers.

You can apply the following operation to this sequence: choose some integer $x$ and move all elements equal to $x$ either to the beginning, or to the end of $a$. Note that you have to move all these elements in one direction in one operation.

For example, if $a = [2, 1, 3, 1, 1, 3, 2]$, you can get the following sequences in one operation (for convenience, denote elements equal to $x$ as $x$-elements):   $[1, 1, 1, 2, 3, 3, 2]$ if you move all $1$-elements to the beginning;  $[2, 3, 3, 2, 1, 1, 1]$ if you move all $1$-elements to the end;  $[2, 2, 1, 3, 1, 1, 3]$ if you move all $2$-elements to the beginning;  $[1, 3, 1, 1, 3, 2, 2]$ if you move all $2$-elements to the end;  $[3, 3, 2, 1, 1, 1, 2]$ if you move all $3$-elements to the beginning;  $[2, 1, 1, 1, 2, 3, 3]$ if you move all $3$-elements to the end;

You have to determine the minimum number of such operations so that the sequence $a$ becomes sorted in non-descending order. Non-descending order means that for all $i$ from $2$ to $n$, the condition $a_{i-1} \le a_i$ is satisfied.

Note that you have to answer $q$ independent queries.

-----Input-----

The first line contains one integer $q$ ($1 \le q \le 3 \cdot 10^5$) — the number of the queries. Each query is represented by two consecutive lines.

The first line of each query contains one integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the number of elements.

The second line of each query contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le n$) — the elements.

It is guaranteed that the sum of all $n$ does not exceed $3 \cdot 10^5$.

-----Output-----

For each query print one integer — the minimum number of operation for sorting sequence $a$ in non-descending order.

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

Output
2
0
1

-----Note-----

In the first query, you can move all $1$-elements to the beginning (after that sequence turn into $[1, 1, 1, 3, 6, 6, 3]$) and then move all...

import sys as _sys

def main():
    q = int(input())
    for i_q in range(q):
        n, = _read_ints()
        a = tuple(_read_ints())
        result = find_min_sorting_cost(sequence=a)
        print(result)

def _read_line():
    result = _sys.stdin.readline()
    assert result[-1] == "\n"
    return result[:-1]

def _read_ints():
    return list(map(int, _read_line().split(" ")))

def find_min_sorting_cost(sequence):
    sequence = tuple(sequence)

    if not sequence:
        return 0

    indices_by_values = {x: [] for x in sequence}
    for i, x in enumerate(sequence):
        indices_by_values[x].append(i)

    borders_by_values = {
        x: (indices[0], indices[-1]) for x, indices in list(indices_by_values.items())
    }

    borders_sorted_by_values = [borders for x, borders in sorted(borders_by_values.items())]

    max_cost_can_keep_n = curr_can_keep_n = 1
    for prev_border, curr_border in zip(borders_sorted_by_values, borders_sorted_by_values[1:]):
        if curr_border[0] > prev_border[1]:
            curr_can_keep_n += 1
        else:
            if curr_can_keep_n > max_cost_can_keep_n:
                max_cost_can_keep_n = curr_can_keep_n
            curr_can_keep_n = 1
    if curr_can_keep_n > max_cost_can_keep_n:
        max_cost_can_keep_n = curr_can_keep_n

    return len(set(sequence)) - max_cost_can_keep_n

def __starting_point():
    main()

__starting_point()


Solve in Python:
You are given a sequence D_1, D_2, ..., D_N of length N.
The values of D_i are all distinct.
Does a tree with N vertices that satisfies the following conditions exist?
 - The vertices are numbered 1,2,..., N.
 - The edges are numbered 1,2,..., N-1, and Edge i connects Vertex u_i and v_i.
 - For each vertex i, the sum of the distances from i to the other vertices is D_i, assuming that the length of each edge is 1.
If such a tree exists, construct one such tree.

-----Constraints-----
 - 2 \leq N \leq 100000
 - 1 \leq D_i \leq 10^{12}
 - D_i are all distinct.

-----Input-----
Input is given from Standard Input in the following format:
N
D_1
D_2
:
D_N

-----Output-----
If a tree with n vertices that satisfies the conditions does not exist, print -1.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines.
The i-th line should contain u_i and v_i with a space in between.
If there are multiple trees that satisfy the conditions, any such tree will be accepted.

-----Sample Input-----
7
10
15
13
18
11
14
19

-----Sample Output-----
1 2
1 3
1 5
3 4
5 6
6 7

The tree shown below satisfies the conditions.

n = int(input())
d = [int(input()) for i in range(n)]

if sum(d)%2 > 0:
    print((-1))
    return

d = sorted([(dd, i) for i, dd in enumerate(d)], reverse = True)
d_to_i = {dd:i for dd, i in d}
n_child = [1]*n
d_child = [0]*n
ans = []
for dd, i in d:
    d_i = dd+2*n_child[i]-n
    if d_i in list(d_to_i.keys()):
        i_next = d_to_i[d_i]
        ans.append((i+1, i_next+1))
        n_child[i_next] += n_child[i]
        d_child[i_next] += d_child[i] + n_child[i]
        if n_child[i_next] == n:
            break
    else:
        print((-1))
        return

d_min, i_min = d[-1]
if d_min == d_child[i_min]:
    for a in ans:
        print((*a))
else:
     print((-1))


Solve in Python:
You are given a sequence a = \{a_1, ..., a_N\} with all zeros, and a sequence b = \{b_1, ..., b_N\} consisting of 0 and 1. The length of both is N.
You can perform Q kinds of operations. The i-th operation is as follows:
 - Replace each of a_{l_i}, a_{l_i + 1}, ..., a_{r_i} with 1.
Minimize the hamming distance between a and b, that is, the number of i such that a_i \neq b_i, by performing some of the Q operations.

-----Constraints-----
 - 1 \leq N \leq 200,000
 - b consists of 0 and 1.
 - 1 \leq Q \leq 200,000
 - 1 \leq l_i \leq r_i \leq N
 - If i \neq j, either l_i \neq l_j or r_i \neq r_j.

-----Input-----
Input is given from Standard Input in the following format:
N
b_1 b_2 ... b_N
Q
l_1 r_1
l_2 r_2
:
l_Q r_Q

-----Output-----
Print the minimum possible hamming distance.

-----Sample Input-----
3
1 0 1
1
1 3

-----Sample Output-----
1

If you choose to perform the operation, a will become \{1, 1, 1\}, for a hamming distance of 1.

n=int(input())
b=list(map(int,input().split()))
ope=[[] for i in range(n)]
Q=int(input())
for i in range(Q):
    l,r=map(int,input().split())
    ope[r-1].append(l-1)

res=b.count(0)

Data=[(-1)**((b[i]==1)+1) for i in range(n)]
for i in range(1,n):
    Data[i]+=Data[i-1]
Data=[0]+Data

for i in range(n):
    ope[i].sort(reverse=True)

# N: 処理する区間の長さ
N=n+1
N0 = 2**(N-1).bit_length()
data = [None]*(2*N0)
INF = (-2**31, -2**31)
# 区間[l, r+1)の値をvに書き換える
# vは(t, value)という値にする (新しい値ほどtは大きくなる)
def update(l, r, v):
    L = l + N0; R = r + N0
    while L < R:
        if R & 1:
            R -= 1
            if data[R-1]:
                data[R-1] = max(v,data[R-1])
            else:
                data[R-1]=v

        if L & 1:
            if data[L-1]:
                data[L-1] = max(v,data[L-1])
            else:
                data[L-1]=v
            L += 1
        L >>= 1; R >>= 1
# a_iの現在の値を取得
def _query(k):
    k += N0-1
    s = INF
    while k >= 0:
        if data[k]:
            s = max(s, data[k])
        k = (k - 1) // 2
    return s
# これを呼び出す
def query(k):
    return _query(k)[1]

for i in range(n+1):
    update(i,i+1,(-Data[i],-Data[i]))
if ope[0]:
    update(1,2,(0,0))

for i in range(1,n):
    val=query(i)
    update(i+1,i+2,(val+Data[i]-Data[i+1],val+Data[i]-Data[i+1]))
    for l in ope[i]:
        val=query(l)
        update(l+1,i+2,(val,val))

print(n-(res+query(n)+Data[n]))


Solve in Python:
You are given a sequence a consisting of n integers. Find the maximum possible value of $a_{i} \operatorname{mod} a_{j}$ (integer remainder of a_{i} divided by a_{j}), where 1 ≤ i, j ≤ n and a_{i} ≥ a_{j}.

-----Input-----

The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·10^5).

The second line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 10^6).

-----Output-----

Print the answer to the problem.

-----Examples-----
Input
3
3 4 5

Output
2

def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = []
    b = res = 0
    for a in aa:
        x += [b] * (a - b)
        b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a < res:
            break
        for b in range(2 * a - 1, maxa + 2 * a, a):
            res = max(res, x[min(b, maxa)] % a)
    print(res)

def __starting_point():
    main()
__starting_point()


Solve in Python:
You are given a sequence a1, a2, ..., aN. Find the smallest possible value of ai + aj, where 1 ≤ i < j ≤ N.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each description consists of a single integer N.
The second line of each description contains N space separated integers - a1, a2, ..., aN respectively.

-----Output-----
For each test case, output a single line containing a single integer - the smallest possible sum for the corresponding test case.

-----Constraints-----

- T = 105, N = 2 : 13 points.
- T = 105, 2 ≤ N ≤ 10 : 16 points.
- T = 1000, 2 ≤ N ≤ 100 : 31 points.
- T = 10, 2 ≤ N ≤ 105 : 40 points.
- 1 ≤ ai ≤ 106

-----Example-----
Input:
1
4
5 1 3 4

Output:
4

-----Explanation-----
Here we pick a2 and a3. Their sum equals to 1 + 3 = 4.

# cook your dish here
t=int(input())
for i in range(t):
 n=int(input())
 l=list(map(int,input().split()))
 l.sort()
 print(l[0]+l[1])


Solve in Python:
You are given a sequence a_1, a_2, ..., a_{n} consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.

Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.

Every element of the sequence must appear in exactly one subsequence.

-----Input-----

The first line of input data contains integer n (1 ≤ n ≤ 10^5) — the length of the sequence.

The second line of input data contains n different integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.

-----Output-----

In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements.

In the next k lines print the description of subsequences in the following format: the number of elements in subsequence c_{i} (0 < c_{i} ≤ n), then c_{i} integers l_1, l_2, ..., l_{c}_{i} (1 ≤ l_{j} ≤ n) — indices of these elements in the original sequence.

Indices could be printed in any order. Every index from 1 to n must appear in output exactly once.

If there are several possible answers, print any of them.

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

Output
4
2 1 3
1 2
2 4 6
1 5

Input
6
83 -75 -49 11 37 62

Output
1
6 1 2 3 4 5 6

-----Note-----

In the first sample output:

After sorting the first subsequence we will get sequence 1 2 3 6 5 4.

Sorting the second subsequence changes nothing.

After sorting the third subsequence we will get sequence 1 2 3 4 5 6.

Sorting the last subsequence changes nothing.

n = int(input())
a = [int(i) for i in input().split()]
a = [i[0] for i in sorted(enumerate(a), key= lambda x:x[1])]
checker = [0 for i in range(n)]
ans_set = []
for i in range(n):
    if checker[i] == 0:
        tmp = set([i])
        next_step = i
        next_step = a[next_step]
        while next_step != i:
            checker[next_step] = 1
            tmp.add(next_step)
            next_step = a[next_step]
        ans_set.append(tmp)
print(len(ans_set))
for tmp in ans_set:
    print(len(tmp), end = " ")
    for j in tmp:
        print(j+1, end = " ")
    print()


Solve in Python:
You are given a sequence of $n$ digits $d_1d_2 \dots d_{n}$. You need to paint all the digits in two colors so that:  each digit is painted either in the color $1$ or in the color $2$;  if you write in a row from left to right all the digits painted in the color $1$, and then after them all the digits painted in the color $2$, then the resulting sequence of $n$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit).

For example, for the sequence $d=914$ the only valid coloring is $211$ (paint in the color $1$ two last digits, paint in the color $2$ the first digit). But $122$ is not a valid coloring ($9$ concatenated with $14$ is not a non-decreasing sequence).

It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.

Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.

-----Input-----

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

The first line of each test case contains an integer $n$ ($1 \le n \le 2\cdot10^5$) — the length of a given sequence of digits.

The next line contains a sequence of $n$ digits $d_1d_2 \dots d_{n}$ ($0 \le d_i \le 9$). The digits are written in a row without spaces or any other separators. The sequence can start with 0.

It is guaranteed that the sum of the values of $n$ for all test cases in the input does not exceed $2\cdot10^5$.

-----Output-----

Print $t$ lines — the answers to each of the test cases in the input.

If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $n$ digits $t_1t_2 \dots t_n$ ($1 \le t_i \le 2$), where $t_i$ is the color the $i$-th digit is painted in. If there are several feasible solutions, print any of them.

If there is no solution, then the corresponding output line should contain a single character '-' (the...

def main():
    from sys import stdin, stdout
    input1 = stdin.readline
    print1 = stdout.write
    for _ in range(int(input1())):
        input1()
        t = tuple(map(int, input1().rstrip('\n')))
        for mid in range(10):
            ans = []
            lasts = [0, 0, 0]
            lasts[2] = mid
            for ti in t:
                if ti < lasts[1]:
                    break
                if ti < lasts[2]:
                    color = 1
                else:
                    color = 2
                ans.append(str(color))
                lasts[color] = ti
            else:
                if lasts[1] == mid:
                    print1(''.join(ans) + '\n')
                    break
        else:
            print1('-\n')

main()


Solve in Python:
You are given a sequence of N$N$ powers of an integer k$k$; let's denote the i$i$-th of these powers by kAi$k^{A_i}$. You should partition this sequence into two non-empty contiguous subsequences; each element of the original sequence should appear in exactly one of these subsequences. In addition, the product of (the sum of elements of the left subsequence) and (the sum of elements of the right subsequence) should be maximum possible.
Find the smallest position at which you should split this sequence in such a way that this product is maximized.

-----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.
- The first line of each test case contains two space-separated integers N$N$ and k$k$.
- The second line contains N$N$ space-separated integers A1,A2,…,AN$A_1, A_2, \dots, A_N$.

-----Output-----
For each test case, print a single line containing one integer — the size of the left subsequence. If there is more than one possible answer, print the smallest possible one.

-----Constraints-----
- 1≤T≤10$1 \le T \le 10$
- 2≤N≤105$2 \le N \le 10^5$
- 2≤k≤109$2 \le k \le 10^9$
- 0≤Ai≤105$0 \le A_i \le 10^5$ for each valid i$i$

-----Subtasks-----
Subtask #1 (30 points):
- 2≤N≤1,000$2 \le N \le 1,000$
- 0≤Ai≤1,000$0 \le A_i \le 1,000$ for each valid i$i$
Subtask #2 (70 points): original constraints

-----Example Input-----
1
5 2
1 1 3 3 5

-----Example Output-----
4

-----Explanation-----
Example case 1: The actual sequence of powers is [21,21,23,23,25]=[2,2,8,8,32]$[2^1, 2^1, 2^3, 2^3, 2^5] = [2, 2, 8, 8, 32]$. The maximum product is 20⋅32=640$20 \cdot 32 = 640$. In the optimal solution, the sequence is partitioned into [2,2,8,8]$[2, 2, 8, 8]$ and [32]$[32]$.

# cook your dish here
t = int(input())
for _ in range(t):
    n,k = [int(d) for d in input().split()]
    l = [int(d) for d in input().split()]
    a1 = min(l)
    l1 = []
    for i in range(n):
     l1.append(k**(l[i]-a1))
    left_sum = 0
    right_sum = 0
    left = 0
    right = n-1
    if k == 1:
     print(n//2)
    else:
     if n <= 3:
      if n == 2:
       print(1)
      else:
       if l1[left] > l1[right]:
        print(1)
       elif l1[right] > l1[left]:
        print(2)
       else:
        print(1)


Solve in Python:
You are given a sequence of a journey in London, UK. The sequence will contain bus **numbers** and TFL tube names as **strings** e.g.

```python
['Northern', 'Central', 243, 1, 'Victoria']
```
Journeys will always only contain a combination of tube names and bus numbers. Each tube journey costs `£2.40` and each bus journey costs `£1.50`. If there are `2` or more adjacent bus journeys, the bus fare is capped for sets of two adjacent buses and calculated as one bus fare for each set.

Your task is to calculate the total cost of the journey and return the cost `rounded to 2 decimal places` in the format (where x is a number): `£x.xx`

def london_city_hacker(journey):
    prices = []

    for stop in journey:
        prices.append(2.4 if type(stop) is str else 1.5)
        if prices[-2:] == [1.5, 1.5]:
            prices[-1] = 0

    return f"£{sum(prices):.2f}"


Solve in Python:
You are given a sequence of integers $A_1, A_2, \dots, A_N$.
You should choose an arbitrary (possibly empty) subsequence of $A$ and multiply each element of this subsequence by $-1$. The resulting sequence should satisfy the following condition: the sum of elements of any contiguous subsequence with length greater than 1 is strictly positive.
You should minimise the sum of elements of the resulting sequence. Find one such sequence with the minimum possible sum.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \dots, A_N$.

-----Output-----
For each test case, print a single line containing $N$ space-separated integers $B_1, B_2, \dots, B_N$. For each valid $i$, $B_i$ must be equal to either $A_i$ (the sign of this element did not change) or $-A_i$ (the sign of this element changed).
If there is more than one answer, you may output any one.

-----Constraints-----
- $1 \le T \le 10^5$
- $2 \le N \le 10^5$
- $1 \le A_i \le 10^9$ for each valid $i$
- the sum of $N$ for all test cases does not exceed $5 \cdot 10^5$

-----Subtasks-----
Subtask #1 (20 points):
- $1 \le T \le 200$
- $2 \le N \le 10$
Subtask #2 (30 points):
- $1 \le T \le 1,000$
- $N \le 2,000$
Subtask #3 (50 points): original constraints

-----Example Input-----
4
4
4 3 1 2
6
1 2 2 1 3 1
5
10 1 2 10 5
4
1 2 1 2

-----Example Output-----
4 3 -1 2
-1 2 2 -1 3 -1
10 -1 2 10 -5
1 2 -1 2

-----Explanation-----
Example case 1: If we change only the sign of $A_3$, we get a sequence $\{4, 3, -1, 2\}$ with sum $8$. This sequence is valid because the sums of all its contiguous subsequences with length $> 1$ are positive. (For example, the sum of elements of the contiguous subsequence $\{A_3, A_4\}$ equals $-1 + 2 = 1 > 0$.)
There are only two valid sequences $\{4, 3, -1, 2\}$ and $\{4, 3, 1, 2\}$ with sums $8$ and $10$...

"""
4
4
4 3 1 2
6
1 2 2 1 3 1
5
10 1 2 10 5
4
1 2 1 2
"""
tests = int(input())

for _ in range(tests):

 n = int(input())
 ls = list(map(int, input().split()))

 if ls[0] < ls[1]:
  ls[0] = -ls[0]

 if ls[-1] < ls[-2]:
  ls[-1] = -ls[-1]

 for i in range(1, n - 1):
  if ls[i] < ls[i - 1] and ls[i] < ls[i + 1]:
   ls[i] = -ls[i]
   '''
      if i > 1 and ls[i - 2] < 0 and ls[i] - ls[i-2] >= ls[i-1]:
       # There can be only one!
       if -ls[i-2] < ls[i]:
        # We win!
        ls[i-2] = -ls[i-2]
        ls[i] = -ls[i]
        #else:
        # They win!
        # Do nothing
      else:
       # We both can go negative
       ls[i] = -ls[i]
      '''

 #print(ls)

 ind = 1

 while ind < n - 1:

  started = False
  pos = []
  while ind < n - 1 and ls[ind] + ls[ind - 1] + ls[ind + 1] <= 0:
   if not started:
    pos.append(ind - 1)
    pos.append(ind + 1)
    started = True
   else:
    pos.append(ind + 1)
   ind += 2

  #print(pos,ls)

  if started:
   rec = [0] * (len(pos) + 1)

   for i in pos:
    ls[i] = -ls[i]

   rec[0] = 0
   rec[1] = ls[pos[0]]

   for i in range(2, len(pos) + 1):
    rec[i] = max(rec[i - 1], ls[pos[i - 1]] + rec[i - 2])

   itr = len(pos)
   while itr > 0:
    if itr == 1 or rec[itr] == ls[pos[itr - 1]] + rec[itr - 2]:
     ls[pos[itr - 1]] = -ls[pos[itr - 1]]
     itr -= 2
    else:
     itr -= 1

  ind += 1

 for i in ls:
  print(i, end = ' ')
 print()


Solve in Python:
You are given a sequence of integers $A_1, A_2, \ldots, A_N$. This sequence is circular ― for each valid $i$, the element $A_{i+1}$ follows after $A_i$, and the element $A_1$ follows after $A_N$.
You may insert any positive integers at any positions you choose in this sequence; let's denote the resulting sequence by $B$. This sequence is also circular. For each pair of its elements $B_s$ and $B_f$, let's denote the (non-circular) sequence created by starting at $B_s$ and moving from each element to the one that follows after it, until we reach $B_f$, by $B(s, f)$. This sequence includes the elements $B_s$ and $B_f$.
For each $K$ from $2$ to $N$ inclusive, find the smallest possible number of elements that need to be inserted into $A$ to form a sequence $B$ for which there is no subsequence $B(p, q)$ such that:
- The size of $B(p, q)$ is at least $K$.
- There is no pair of consecutive elements in $B(p, q)$ such that their GCD is equal to $1$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print a single line containing $N-1$ space-separated integers. For each $i$ ($1 \le i \le N-1$), the $i$-th of these integers should be the smallest number of inserted elements in a valid sequence $B$ for $K = i+1$.

-----Constraints-----
- $1 \le T \le 2,000$
- $2 \le N \le 10^5$
- $1 \le A_i \le 10^9$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $2 \cdot 10^6$

-----Example Input-----
1
5
3 6 4 5 9

-----Example Output-----
3 1 1 0

from math import gcd
from itertools import groupby

def gcd_split(seq):
 gcds= [int(gcd(a,b)==1) for a,b in zip(seq[1:],seq[:-1])]
 gcds.append(int(gcd(seq[0],seq[-1])==1))
 # print(gcds)
 if max(gcds)==0:
  return -1
 else:
  splits=[len(list(x))+1 for num,x in groupby(gcds) if num==0]
  # print(splits)
  if gcds[0]==gcds[-1]==0:
   splits[0] += splits[-1]-1
   splits = splits[:-1]
  return splits

for _ in range(int(input())):
 N=int(input())
 A=[int(x) for x in input().split()]
 split = gcd_split(A)
 # print(split)

 res=[]
 if split!=-1:
  for K in range(2,N+1):
   temp=(x for x in split if x>=K)
   ins = sum([(x//(K-1)-1 if x%(K-1)==0 else x//(K-1)) for x in temp])
   if ins==0:
    break
   else:
    res.append(ins)
 else:
  for K in range(2,N+1):
   ins = N//(K-1)+(N%(K-1)>0)
   if ins==0:
    break
   else:
    res.append(ins)

 res = res + [0]*(N-1 -len(res))
 print(*res)


Solve in Python:
You are given a sequence of integers $A_1,A_2,…,A_N$ and a magical non-zero integer $x$
You have to select a subsegment of sequence A (possibly empty), and replace the elements in that subsegment after dividing them by x.
Formally, replace any one subsegment $A_l, A_{l+1}, ..., A_r$ with $A_l/x, A_{l+1}/x, ..., A_r/x$ where $l \leq r$
What is the minimum possible sum you can obtain?
Note: The given operation can only be performed once

-----Input -----
- The first line of the input contains two positive integer n denoting the size of array, and x
denoting the magical integer
- Next line contains $N$ space separated integers

-----Output-----
Single line containing one real number, denoting the minimum possible sum you can obtain. Your answer will be considered correct if its absolute or relative error does not exceed $10^{-2}$

-----Constraints-----
- $1 \leq n \leq 10^3$
- $1 \leq |x| \leq 10^3$
- $ |A_i| \leq 10^3$

-----Sample Input-----
3 2
1 -2 3

-----Sample Output-----
0.5

-----Explanation-----
Array 1 -2 3, selecting subsegment {3}, you get 1 -2 1.5, which gives $sum=0.5$

n,k=list(map(int,input().split()))
l=list(map(int,input().split()))
i=0
x=sum(l)
d=x
m=0
for i in range(n):
 c=0
 for j in range(i,n):
  c+=l[j]
  m=max(c,m)
d-=m
d+=m/k

print(d)


Solve in Python:
You are given a sequence of n integers a1, a2, ..., an and an integer d.
Find the length of the shortest non-empty contiguous subsequence with sum of elements at least d. Formally, you should find the smallest positive integer k with the following property: there is an integer s (1 ≤ s ≤ N-k+1) such that as + as+1 + ... + as+k-1 ≥ d.

-----Input-----

- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains two space-separated integers n and d.
- The second line contains n space-separated integers a1, a2, ..., an.

-----Output-----
For each test case, print a single line containing one integer — the length of the shortest contiguous subsequence with sum of elements ≥ d. If there is no such subsequence, print -1 instead.

-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 105
- -109 ≤ d ≤ 109
- -104 ≤ ai ≤ 104
- 1 ≤ sum of n over all test cases ≤ 2 · 105

-----Example-----
Input:

2
5 5
1 2 3 1 -5
5 1
1 2 3 1 -5

Output:

2
1

# cook your dish here

import collections

def shortestSubarray(A, K):

  N = len(A)
  P = [0]

  for x in A:
   P.append(P[-1] + x)

  #Want smallest y-x with Py - Px >= K
  ans = N+1 # N+1 is impossible
  monoq = collections.deque() #opt(y) candidates, represented as indices             of P
  for y, Py in enumerate(P):
   #Want opt(y) = largest x with Px <= Py - K
   if not monoq:
    if Py>=K: return 1
   while monoq and Py <= P[monoq[-1]]:
    monoq.pop()

   while monoq and Py - P[monoq[0]] >= K:
    ans = min(ans, y - monoq.popleft())

   monoq.append(y)

  return ans if ans < N+1 else -1

for t in range(int(input())):
 N, D = [int(x) for x in input().split()]

 A = [int(x) for x in input().split()]

 print(shortestSubarray(A, D))


Solve in Python:
You are given a sequence of n integers a_1, a_2, ..., a_{n}.

Determine a real number x such that the weakness of the sequence a_1 - x, a_2 - x, ..., a_{n} - x is as small as possible.

The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.

The poorness of a segment is defined as the absolute value of sum of the elements of segment.

-----Input-----

The first line contains one integer n (1 ≤ n ≤ 200 000), the length of a sequence.

The second line contains n integers a_1, a_2, ..., a_{n} (|a_{i}| ≤ 10 000).

-----Output-----

Output a real number denoting the minimum possible weakness of a_1 - x, a_2 - x, ..., a_{n} - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10^{ - 6}.

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

Output
1.000000000000000

Input
4
1 2 3 4

Output
2.000000000000000

Input
10
1 10 2 9 3 8 4 7 5 6

Output
4.500000000000000

-----Note-----

For the first case, the optimal value of x is 2 so the sequence becomes  - 1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case.

For the second sample the optimal value of x is 2.5 so the sequence becomes  - 1.5,  - 0.5, 0.5, 1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case.

def f(x):
    bi = 0
    ci = 0
    cnt1 = -10 ** 10
    minsum1 = 10 ** 10
    cnt2 = -10 ** 10
    minsum2 = 10 ** 10
    for i in range(len(A)):
        if bi - minsum1 > cnt1:
            cnt1 = bi - minsum1
        if bi <= minsum1:
            minsum1 = bi
        if ci - minsum2 > cnt2:
            cnt2 = ci - minsum2
        if ci <= minsum2:
            minsum2 = ci
        bi += A[i] - x
        ci += x - A[i]
    if bi - minsum1 > cnt1:
        cnt1 = bi - minsum1
    if bi <= minsum1:
        minsum1 = bi
    if ci - minsum2 > cnt2:
        cnt2 = ci - minsum2
    if ci <= minsum2:
        minsum2 = ci
    return max(cnt1, cnt2, 0)

n = int(input())
A = list(map(int, input().split()))
l = min(A)
r = max(A)
for _ in range(70):
    p = l + (r - l) / 3
    q = r - (r - l) / 3
    x = f(p)
    y = f(q)
    if x > y:
        l = p
    elif y > x:
        r = q
    else:
        l = p
        r = q
print(f(l))


Solve in Python:
You are given a sequence of non-negative integers $A_1, A_2, \ldots, A_N$. At most once, you may choose a non-negative integer $X$ and for each valid $i$, change $A_i$ to $A_i \oplus X$ ($\oplus$ denotes bitwise XOR).
Find the minimum possible value of the sum of all elements of the resulting sequence.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of the input contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.

-----Output-----
For each test case, print a single line containing one integer ― the minimum possible sum.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^5$
- $1 \le A_i \le 10^9$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $10^6$

-----Subtasks-----
Subtask #1 (50 points):
- $1 \le N \le 10^3$
- $1 \le A_i \le 10^3$ for each valid $i$
Subtask #2 (50 points): original constraints

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

-----Example Output-----
14
0
2

-----Explanation-----
Example case 1: If we choose $X = 6$, the sequence becomes $(4, 5, 2, 3, 0)$.
Example case 2: We can choose $X = 7$ to make all elements of the resulting sequence equal to $0$.
Example case 3: We can choose $X = 1$. The sequence becomes $(0, 0, 2)$, with sum $2$.

# cook your dish here
for _ in range(int(input())):
 n = int(input())
 arr = list(map(int, input().split()))
 x, cur_bit = 0, 0 #max bit is the highest value bit (0-indexed)
 bitset = {}
 for ele in arr:
  while ele:
   if ele & 1: bitset[cur_bit] = bitset.get(cur_bit,0)+1
   cur_bit += 1
   ele >>= 1
  cur_bit = 0
 for b in bitset:
  if bitset[b] > n-bitset[b]: x |= (1 << b)
 total = 0
 for ele in arr: total += ele^x
 print(total)


Solve in Python:
You are given a series of video clips from a sporting event that lasted T seconds.  These video clips can be overlapping with each other and have varied lengths.
Each video clip clips[i] is an interval: it starts at time clips[i][0] and ends at time clips[i][1].  We can cut these clips into segments freely: for example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7].
Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event ([0, T]).  If the task is impossible, return -1.

Example 1:
Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], T = 10
Output: 3
Explanation:
We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut [1,9] into segments [1,2] + [2,8] + [8,9].
Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].

Example 2:
Input: clips = [[0,1],[1,2]], T = 5
Output: -1
Explanation:
We can't cover [0,5] with only [0,1] and [1,2].

Example 3:
Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], T = 9
Output: 3
Explanation:
We can take clips [0,4], [4,7], and [6,9].

Example 4:
Input: clips = [[0,4],[2,8]], T = 5
Output: 2
Explanation:
Notice you can have extra video after the event ends.

Constraints:

1 <= clips.length <= 100
0 <= clips[i][0] <= clips[i][1] <= 100
0 <= T <= 100

import math

class Solution:
    def videoStitching(self, clips: List[List[int]], T: int) -> int:
        clips.sort()
        longest = sorted(clips, key=lambda a: a[1])[-1][1]
        memo = [[None for i in range(longest + 1)] for i in range(len(clips))]

        def dp(i, start):
            if start >= T:
                return 0

            curr = clips[i]
            if curr[0] > start:
                return math.inf
            elif i == len(clips) - 1:
                if curr[1] < T:
                    return math.inf
                return 1

            # Pick first clip
            if memo[i + 1][curr[1]] == None:
                memo[i + 1][curr[1]] = dp(i + 1, curr[1])

            #Don't pick first clip
            if memo[i + 1][start] == None:
                memo[i + 1][start] = dp(i + 1, start)

            return min(1 + memo[i + 1][curr[1]], memo[i + 1][start])

        res = dp(0, 0)
        return res if res != math.inf else -1


Solve in Python:
You are given a set $S$ and $Q$ queries. Initially, $S$ is empty. In each query:
- You are given a positive integer $X$.
- You should insert $X$ into $S$.
- For each $y \in S$ before this query such that $y \neq X$, you should also insert $y \oplus X$ into $S$ ($\oplus$ denotes the XOR operation).
- Then, you should find two values $E$ and $O$: the number of elements of $S$ with an even number of $1$-s and with an odd number of $1$-s in the binary representation, respectively.
Note that a set cannot have duplicate elements, so if you try to insert into $S$ an element that is already present in $S$, then nothing happens.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $Q$.
- Each of the next $Q$ lines contains a single integer $X$ describing a query.

-----Output-----
For each query, print a single line containing two space-separated integers $E$ and $O$.

-----Constraints-----
- $1 \le T \le 5$
- $1 \le Q, X \le 10^5$

-----Subtasks-----
Subtask #1 (30 points):
- $1 \le Q \le 1,000$
- $1 \le X \le 128$
Subtask #2 (70 points): original constraints

-----Example Input-----
1
3
4
2
7

-----Example Output-----
0 1
1 2
3 4

-----Explanation-----
Example case 1:
- Initially, the set is empty: $S = \{\}$.
- After the first query, $S = \{4\}$, so there is only one element with an odd number of $1$-s in the binary representation ("100").
- After the second query, $S = \{4,2,6\}$, there is one element with an even number of $1$-s in the binary representation ($6$ is "110") and the other two elements have an odd number of $1$-s.
- After the third query, $S = \{4,2,6,7,3,5,1\}$.

# fast io
import sys
def fop(s): sys.stdout.write(str(s)+'\n')
def fip(): return sys.stdin.readline()
fintinp = lambda : int(fip())
def flistinp(func= int): return list(map(func,fip().split()))
def fnsepline(n,func=str): return [func(fip()) for _ in range(n)]
#-------------------code------------------------
def even(x):
 x = bin(x).count('1')
 return x%2==0

for _ in range(fintinp()):
 q =fintinp()
 o = e =0
 nums = set()
 for qn in range(q):
  qn = fintinp()
  if qn not in nums:
   if even(qn): e+=1
   else: o+=1

   for n in set(nums):
    x = n^qn
    if x not in nums:
     if even(x): e+=1
     else: o+=1

     nums.add(x)

  nums.add(qn)
  print(e,o)


Solve in Python:
You are given a set Y of n distinct positive integers y_1, y_2, ..., y_{n}.

Set X of n distinct positive integers x_1, x_2, ..., x_{n} is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X:  Take any integer x_{i} and multiply it by two, i.e. replace x_{i} with 2·x_{i}.  Take any integer x_{i}, multiply it by two and add one, i.e. replace x_{i} with 2·x_{i} + 1.

Note that integers in X are not required to be distinct after each operation.

Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal.

Note, that any set of integers (or its permutation) generates itself.

You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y.

The second line contains n integers y_1, ..., y_{n} (1 ≤ y_{i} ≤ 10^9), that are guaranteed to be distinct.

-----Output-----

Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them.

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

Output
4 5 2 3 1

Input
6
15 14 3 13 1 12

Output
12 13 14 7 3 1

Input
6
9 7 13 17 5 11

Output
4 5 2 6 3 1

def main():
    from heapq import heapify, heapreplace
    input()
    s = set(map(int, input().split()))
    xx = [-x for x in s]
    heapify(xx)
    while True:
        x = -xx[0]
        while x != 1:
            x //= 2
            if x not in s:
                s.add(x)
                heapreplace(xx, -x)
                break
        else:
            break
    print(' '.join(str(-x) for x in xx))

def __starting_point():
    main()

__starting_point()


Solve in Python:
You are given a set of `n` segments on the axis `Ox`, each segment has integer endpoints between `0` and `m` inclusive.
 Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers li and ri — coordinates of the left and of the right endpoints.

 Consider all integer points between `0` and `m` inclusive. Your task is to print all such points that don't belong to any segment. The point x belongs to the segment `[l;r]` if and only if `l ≤ x ≤ r`.

**Input:**
 `m` — the upper bound for coordinates;
 array of coordinates li and ri `0 ≤ li ≤ ri ≤ m` — the endpoints of the `i`-th segment. Segments may intersect, overlap or even coincide with each other.

**Output:**
 All points from `0` to `m` that don't belong to any segment.

**Examples:**
```python
segments(5, [(2,2),(1,2),(5,5)]) => [0,3,4]
segments(7, [(0,7)]) => []
```

def segments(m, a):
    segments = {n for l, r in a for n in range(l, r+1)}
    return [n for n in range(m+1) if n not in segments]

# one-liner: [n for n in range(m+1) if n not in {n for l, r in a for n in range(l, r+1)}]


Solve in Python:
You are given a set of n pens, each of them can be red, blue, green, orange, and violet in color. Count a minimum number of pens that should be taken out from the set so that any two neighboring pens have different colors. Pens are considered to be neighboring if there are no other pens between them.

-----Input:-----
-
The first line contains t denoting the number of test cases.
-
The first line of each test case will contain a single integer n.
-
The second line of each test case will contain a string s.
(s contains only 'R', 'B', 'G', 'O', and 'V' characters denoting red, blue, green, orange, and violet respectively)

-----Output:-----
For each test case, print single line containing one integer - The minimum number of pens that need to be taken out.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq n \leq 1000$

-----Sample Input:-----
2
5
RBBRG
5
RBGOV

-----Sample Output:-----
1
0

-----EXPLANATION:-----
In first test case, two blue pens are neighboring each other, if we take out any one of them then the string will be RBRG in which each pen has different neighbors.
In second test case, no pen needs to be taken out as each pen has different neighbors.

t=int(input())
for _ in range(t):
    n=int(input())
    a=input()
    count=0
    i=0
    j=1
    while(i<n and j<n):
        if(a[i]==a[j]):
            count=count+1
        i=i+1
        j=j+1
    print(count)


Solve in Python:
You are given a set of points in the 2D plane. You start at the point with the least X and greatest Y value, and end at the point with the greatest X and least Y value. The rule for movement is that you can not move to a point with a lesser X value as compared to the X value of the point you are on. Also for points having the same X value, you need to visit the point with the greatest Y value before visiting the next point with the same X value. So, if there are 2 points: (0,4 and 4,0) we would start with (0,4) - i.e. least X takes precedence over greatest Y. You need to visit every point in the plane.

-----Input-----
You will be given an integer t(1<=t<=20) representing the number of test cases. A new line follows; after which the t test cases are given. Each test case starts with a blank line followed by an integer n(2<=n<=100000), which represents the number of points to follow. This is followed by a new line. Then follow the n points, each being a pair of integers separated by a single space; followed by a new line. The X and Y coordinates of each point will be between 0 and 10000 both inclusive.

-----Output-----
For each test case, print the total distance traveled by you from start to finish; keeping in mind the rules mentioned above, correct to 2 decimal places. The result for each test case must be on a new line.

-----Example-----
Input:
3

2
0 0
0 1

3
0 0
1 1
2 2

4
0 0
1 10
1 5
2 2

Output:
1.00
2.83
18.21

For the third test case above, the following is the path you must take:
0,0 -> 1,10
1,10 -> 1,5
1,5 -> 2,2
= 18.21

def __starting_point():
    TC = int(input())
    for _ in range(TC):
        line = input()
        N = int(input())
        arr = []
        for _ in range(N):
            x, y = list(map(int, input().strip().split()))
            arr.append((x, y))
        arr.sort(key=lambda a: (a[0], a[1] * -1))
        dist = 0
        for i in range(1, N):
            x1 = arr[i][0]
            y1 = arr[i][1]
            x2 = arr[i-1][0]
            y2 = arr[i-1][1]
            d = ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5
            dist += d

        print("{:0.2f}".format(dist))
__starting_point()


Solve in Python:
You are given a set of size $m$ with integer elements between $0$ and $2^{n}-1$ inclusive. Let's build an undirected graph on these integers in the following way: connect two integers $x$ and $y$ with an edge if and only if $x \& y = 0$. Here $\&$ is the bitwise AND operation. Count the number of connected components in that graph.

-----Input-----

In the first line of input there are two integers $n$ and $m$ ($0 \le n \le 22$, $1 \le m \le 2^{n}$).

In the second line there are $m$ integers $a_1, a_2, \ldots, a_m$ ($0 \le a_{i} < 2^{n}$) — the elements of the set. All $a_{i}$ are distinct.

-----Output-----

Print the number of connected components.

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

Output
2

Input
5 5
5 19 10 20 12

Output
2

-----Note-----

Graph from first sample:

$0$

Graph from second sample:

[Image]

n, m = map(int, input().split())
a = set(map(int, input().split()))

y = 2 ** n
mk = [0] * (2 * y)
cur = 0
for x in a:
    if mk[x]: continue
    mk[x] = 1
    st = [x]
    def push(v):
        if not mk[v]: mk[v] = 1; st.append(v)
    while st:
        u = st.pop()
        if u < y:
            push(y + u)
        else:
            for b in range(n):
                v = u | 1 << b
                push(v)
            v = y - 1 - (u - y)
            if v in a: push(v)
    cur += 1

print(cur)


Solve in Python:
You are given a special jigsaw puzzle consisting of $n\cdot m$ identical pieces. Every piece has three tabs and one blank, as pictured below. $\{3$

The jigsaw puzzle is considered solved if the following conditions hold:  The pieces are arranged into a grid with $n$ rows and $m$ columns.  For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece.

Through rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.

-----Input-----

The test consists of multiple test cases. The first line contains a single integer $t$ ($1\le t\le 1000$) — the number of test cases. Next $t$ lines contain descriptions of test cases.

Each test case contains two integers $n$ and $m$ ($1 \le n,m \le 10^5$).

-----Output-----

For each test case output a single line containing "YES" if it is possible to solve the jigsaw puzzle, or "NO" otherwise. You can print each letter in any case (upper or lower).

-----Example-----
Input
3
1 3
100000 100000
2 2

Output
YES
NO
YES

-----Note-----

For the first test case, this is an example solution:  [Image]

For the second test case, we can show that no solution exists.

For the third test case, this is an example solution: $\left\{\begin{array}{l}{3} \\{3} \end{array} \right\}$

import sys

readline = sys.stdin.readline

ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: list(map(int, readline().split()))
nl = lambda: list(map(int, readline().split()))

def solve():
    n, m = nm()
    if min(n, m) == 1 or max(n, m) == 2:
        print('YES')
    else:
        print('NO')

# solve()

T = ni()
for _ in range(T):
    solve()


Solve in Python:
You are given a square matrix $M$ with $N$ rows (numbered $1$ through $N$) and $N$ columns (numbered $1$ through $N$). Initially, all the elements of this matrix are equal to $A$. The matrix is broken down in $N$ steps (numbered $1$ through $N$); note that during this process, some elements of the matrix are simply marked as removed, but all elements are still indexed in the same way as in the original matrix. For each valid $i$, the $i$-th step consists of the following:
- Elements $M_{1, N-i+1}, M_{2, N-i+1}, \ldots, M_{i-1, N-i+1}$ are removed.
- Elements $M_{i, N-i+1}, M_{i, N-i+2}, \ldots, M_{i, N}$ are removed.
- Let's denote the product of all $2i-1$ elements removed in this step by $p_i$. Each of the remaining elements of the matrix (those which have not been removed yet) is multiplied by $p_i$.
Find the sum $p_1 + p_2 + p_3 + \ldots + p_N$. Since this number could be very large, compute it modulo $10^9+7$.

-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains two space-separated integers $N$ and $A$.

-----Output-----
For each test case, print a single line containing one integer ― the sum of products at each step modulo $10^9+7$.

-----Constraints-----
- $1 \le T \le 250$
- $1 \le N \le 10^5$
- $0 \le A \le 10^9$
- the sum of $N$ over all test cases does not exceed $10^5$

-----Example Input-----
1
3 2

-----Example Output-----
511620149

-----Explanation-----
Example case 1:

# cook your dish here
mod=1000000007
for _ in range(int(input())):
 n,a=list(map(int, input().split()))
 p,ans=1,0
 for i in range(n):
  a1=pow(a, p, mod)
  ans=(ans+a1)%mod
  a=(a*a1)%mod
  p+=2

 print(ans)


Solve in Python:
You are given a string $S$ and an integer $L$. A operation is described as :- "You are allowed to pick any substring from first $L$ charcaters of $S$, and place it at the end of the string $S$.
A string $A$ is a substring of an string $B$ if $A$ can be obtained from $B$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) elements from the end.
Find the lexographically smallest string after performing this opertaion any number of times (possibly zero).
For example $S$ = "codechef" and $L=4$. Then, we can take substring "ode" from S[0-3] and place it at end of the string $S$ = "cchefode".

-----Input:-----
- First line will contain $T$, number of testcases.
- Then each of the N lines contain an integer $L$ and a string $S$.

-----Output:-----
For each testcase, output in a single line answer lexographically smallest string.

-----Constraints-----
- $1 \leq T \leq 10^4$
- $2 \leq |S| \leq 10^3$
- $1 \leq L \leq N $

-----Sample Input:-----
2
1 rga
2 cab

-----Sample Output:-----
arg
abc

-----EXPLANATION:-----
In the first testcase:
substring 'r' is picked and placed at the end of the string. rga -> gar
Then performing same operation gives :- gar -> arg

def solve(s,l,ans):
    n = len(s)
    s = list(s)
    if l > 1:
        s.sort()
        ans.append(s)
        return

    indices = []
    min_val = min(s)
    for i in range(len(s)):
        if s[i] == min_val:
            indices.append((i,1))

    while True:
        min_val = 'z'
        found = False
        for index,count in indices:
            min_val = min(min_val,s[index])
            if count == n:
                found = True

        if found:
            break

        new_indices = []
        for index,count in indices:
            if s[index] == min_val:
                if index+1 == n:
                    new_indices.append((0,count+1))
                else:
                    new_indices.append((index+1,count+1))

        indices = new_indices[:]

    s1 = []
    index = indices[0][0]
    count = 0
    while index >= 0:
        s1.append(s[index])
        count += 1
        index -= 1

    index = n-1
    while count != n:
        s1.append(s[index])
        index -= 1
        count += 1

    s1.reverse()
    ans.append(s1)

def main():
    t = int(input())
    ans = []
    for i in range(t):
        l,s = map(str,input().split())
        l = int(l)
        solve(s,l,ans)

    for i in ans:
        for j in i:
            print(j,end = '')

        print()

main()


Solve in Python:
You are given a string $S$. Find the number of ways to choose an unordered pair of non-overlapping non-empty substrings of this string (let's denote them by $s_1$ and $s_2$ in such a way that $s_2$ starts after $s_1$ ends) such that their concatenation $s_1 + s_2$ is a palindrome.
Two pairs $(s_1, s_2)$ and $(s_1', s_2')$ are different if $s_1$ is chosen at a different position from $s_1'$ or $s_2$ is chosen at a different position from $s_2'$.

-----Input-----
The first and only line of the input contains a single string $S$.

-----Output-----
Print a single line containing one integer — the number of ways to choose a valid pair of substrings.

-----Constraints-----
- $1 \le |S| \le 1,000$
- $S$ contains only lowercase English letters

-----Subtasks-----
Subtask #1 (25 points): $|S| \le 100$
Subtask #2 (75 points): original constraints

-----Example Input-----
abba

-----Example Output-----
7

-----Explanation-----
The following pairs of substrings can be chosen: ("a", "a"), ("a", "ba"), ("a", "bba"), ("ab", "a"), ("ab", "ba"), ("abb", "a"), ("b", "b").

# cook your dish here
st = str(input())

def checkpal(i,j,k,l):

 a=i
 b=l
 while(a<b):
  if st[a] != st[b]:

   return -1

  if(a==j):
   a = k-1
  if(b==k):
   b = j+1

  a+=1
  b-=1
 # print(i,j,k,l)
 # print("yes")
 return 1

l = len(st)
count = 0
for i in range(l):
 for j in range(i,l):
  for k in range(j+1,l):
   for m in range(k,l):
    if checkpal(i,j,k,m) == 1:
     count += 1

print(count)


Solve in Python:
You are given a string $s$ of even length $n$. String $s$ is binary, in other words, consists only of 0's and 1's.

String $s$ has exactly $\frac{n}{2}$ zeroes and $\frac{n}{2}$ ones ($n$ is even).

In one operation you can reverse any substring of $s$. A substring of a string is a contiguous subsequence of that string.

What is the minimum number of operations you need to make string $s$ alternating? A string is alternating if $s_i \neq s_{i + 1}$ for all $i$. There are two types of alternating strings in general: 01010101... or 10101010...

-----Input-----

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

The first line of each test case contains a single integer $n$ ($2 \le n \le 10^5$; $n$ is even) — the length of string $s$.

The second line of each test case contains a binary string $s$ of length $n$ ($s_i \in$ {0, 1}). String $s$ has exactly $\frac{n}{2}$ zeroes and $\frac{n}{2}$ ones.

It's guaranteed that the total sum of $n$ over test cases doesn't exceed $10^5$.

-----Output-----

For each test case, print the minimum number of operations to make $s$ alternating.

-----Example-----
Input
3
2
10
4
0110
8
11101000

Output
0
1
2

-----Note-----

In the first test case, string 10 is already alternating.

In the second test case, we can, for example, reverse the last two elements of $s$ and get: 0110 $\rightarrow$ 0101.

In the third test case, we can, for example, make the following two operations:   11101000 $\rightarrow$ 10101100;  10101100 $\rightarrow$ 10101010.

import sys

def main():
    n = int(sys.stdin.readline().strip())
    #n, m = map(int, sys.stdin.readline().split())
    #q = list(map(int, sys.stdin.readline().split()))
    s = sys.stdin.readline().strip()
    res = 0
    i = 0
    while i < n:
        while i < n and s[i] != "1":
            i += 1
        if i >= n:
            break
        while i < n and s[i] == "1":
            i += 1
            res += 1
            #print(i, res)
        i += 1
        res -= 1
        #print(" ", i, res)
    i = 0
    ans = 0
    while i < n:
        while i < n and s[i] != "0":
            i += 1
        if i >= n:
            break
        while i < n and s[i] == "0":
            i += 1
            ans += 1
            #print(i, res)
        i += 1
        ans -= 1
        #print(" ", i, res)
    print(max(ans, res))

for i in range(int(sys.stdin.readline().strip())):
    main()


Solve in Python:
You are given a string $s$. And you have a function $f(x)$ defined as:
f(x) = 1, if $x$ is a vowel
f(x) = 0, if $x$ is a constant

Your task is to apply the above function on all the characters in the string s and convert
the obtained binary string in decimal number $M$.
Since the number $M$ can be very large, compute it modulo $10^9+7$.

-----Input:-----
- The first line of the input contains a single integer $T$ i.e the no. of test cases.
- Each test line contains one String $s$ composed of lowercase English alphabet letters.

-----Output:-----
For each case, print a single line containing one integer $M$ modulo $10^9 + 7$.

-----Constraints-----
- $1 ≤ T ≤ 50$
- $|s|≤10^5$

-----Subtasks-----
- 20 points : $|s|≤30$
- 80 points : $ \text{original constraints}$

-----Sample Input:-----
1
hello

-----Sample Output:-----
9

t=int(input())
l=['a','e','i','o','u']
for i in range(t):
 s=input()
 k=[]
 for j in s:
  if j in l:
   k.append(1)
  else:
   k.append(0)
 r=bin(int(''.join(map(str, k)), 2) << 1)
 print(int(r,2)//2)


Solve in Python:
You are given a string $s[1 \dots n]$ consisting of lowercase Latin letters. It is guaranteed that $n = 2^k$ for some integer $k \ge 0$.

The string $s[1 \dots n]$ is called $c$-good if at least one of the following three conditions is satisfied:  The length of $s$ is $1$, and it consists of the character $c$ (i.e. $s_1=c$); The length of $s$ is greater than $1$, the first half of the string consists of only the character $c$ (i.e. $s_1=s_2=\dots=s_{\frac{n}{2}}=c$) and the second half of the string (i.e. the string $s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$) is a $(c+1)$-good string;  The length of $s$ is greater than $1$, the second half of the string consists of only the character $c$ (i.e. $s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$) and the first half of the string (i.e. the string $s_1s_2 \dots s_{\frac{n}{2}}$) is a $(c+1)$-good string.

For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.

In one move, you can choose one index $i$ from $1$ to $n$ and replace $s_i$ with any lowercase Latin letter (any character from 'a' to 'z').

Your task is to find the minimum number of moves required to obtain an 'a'-good string from $s$ (i.e. $c$-good string for $c=$ 'a'). It is guaranteed that the answer always exists.

You have to answer $t$ independent test cases.

Another example of an 'a'-good string is as follows. Consider the string $s = $"cdbbaaaa". It is an 'a'-good string, because:  the second half of the string ("aaaa") consists of only the character 'a';  the first half of the string ("cdbb") is 'b'-good string, because:   the second half of the string ("bb") consists of only the character 'b';  the first half of the string ("cd") is 'c'-good string, because:   the first half of the string ("c") consists of only the character 'c';  the second half of the string ("d") is 'd'-good string.

-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case...

def find(st,count,ans,low,high,char):
	#print(st,low,high,"ss")
	if high-low==0:
		if chr(char)==st[high]:
			ans.append(count)
		else:
			ans.append(count+1)
	else:
		check=0
		mid=(high+low)//2
		for k in st[low:mid+1]:
			if k!=chr(char):
				check+=1
		find(st,count+check,ans,mid+1,high,char+1)
		check=0
		for k in st[mid+1:high+1]:
			if k!=chr(char):
				check+=1
		find(st,count+check,ans,low,mid,char+1)

for i in range(int(input())):
	n=int(input())
	st=input()
	ans=[]
	find(st,0,ans,0,n-1,97)
	print(min(ans))


Solve in Python:
You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.

A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest".

A palindrome is a string that reads the same forward or backward.

The length of string B should be at most 10^4. It is guaranteed that there always exists such string.

You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 10^4.

-----Input-----

First line contains a string A (1 ≤ |A| ≤ 10^3) consisting of lowercase Latin letters, where |A| is a length of A.

-----Output-----

Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 10^4. If there are many possible B, print any of them.

-----Examples-----
Input
aba

Output
aba
Input
ab

Output
aabaa

-----Note-----

In the first example, "aba" is a subsequence of "aba" which is a palindrome.

In the second example, "ab" is a subsequence of "aabaa" which is a palindrome.


Solve in Python:
You are given a string S consisting of a,b and c. Find the number of strings that can be possibly obtained by repeatedly performing the following operation zero or more times, modulo 998244353:
 - Choose an integer i such that 1\leq i\leq |S|-1 and the i-th and (i+1)-th characters in S are different. Replace each of the i-th and (i+1)-th characters in S with the character that differs from both of them (among a, b and c).

-----Constraints-----
 - 2 \leq |S| \leq 2 × 10^5
 - S consists of a, b and c.

-----Input-----
Input is given from Standard Input in the following format:
S

-----Output-----
Print the number of strings that can be possibly obtained by repeatedly performing the operation, modulo 998244353.

-----Sample Input-----
abc

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

abc, aaa and ccc can be obtained.

from collections import defaultdict
import sys
S=input()
N=len(S)
if N==3:
    if S[0]==S[1]:
        if S[1]==S[2]:
            print((1))
        else:
            print((6))
    else:
        if S[0]==S[2]:
            print((7))
        elif S[1]==S[2]:
            print((6))
        else:
            print((3))
    return
a=S[0]
t=1
for i in range(N):
    if S[i]!=a:
        t=0
        break
if t==1:
    print((1))
    return

mod=998244353
M=0
for s in S:
    if s=='b':
        M+=1
    elif s=='c':
        M+=2
    M%=3
dp=[]
for i in range(2):
    for k in range(3):
        for l in range(3):
            dp.append((i,k,l))
dd=[[[0]*3 for i in range(3)] for i in range(2)]
for i in range(3):
    dd[0][i][i]=1
for k in range(2,N+1):
    nd=[[[0]*3 for i in range(3)] for i in range(2)]
    for p in dp:
        con,moji,m=p
        n=dd[con][moji][m]
        #print(con,moji,m)
        if con==0:
            for k in range(3):
                if moji==k:
                    nd[1][k][ (m + k) % 3] += n
                    nd[1] [k ][(m + k) % 3] %=mod
                else:
                    nd[0][k][(m+k)%3]+=n
                    nd[0][ k] [(m+k) % 3] %=mod
        else:
            for k in range(3):
                nd[1][k][(m + k) % 3] += n
                nd[1][k][(m + k) % 3] %=mod
    #print(nd)
    dd=nd
flag=1
for i in range(N-1):
    if S[i]==S[i+1]:
        flag=0
ans=flag
for k in range(3):
    ans+=dd[1][k][M]
    ans%=mod
print(ans)


Solve in Python:
You are given a string S consisting of lowercase English letters.
Determine whether we can turn S into a palindrome by repeating the operation of swapping two adjacent characters. If it is possible, find the minimum required number of operations.

-----Constraints-----
 - 1 \leq |S| \leq 2 × 10^5
 - S consists of lowercase English letters.

-----Input-----
Input is given from Standard Input in the following format:
S

-----Output-----
If we cannot turn S into a palindrome, print -1. Otherwise, print the minimum required number of operations.

-----Sample Input-----
eel

-----Sample Output-----
1

We can turn S into a palindrome by the following operation:
 - Swap the 2-nd and 3-rd characters. S is now ele.

import sys
from collections import deque, defaultdict
import copy
import bisect
sys.setrecursionlimit(10 ** 9)
import math
import heapq
from itertools import product, permutations,combinations
import fractions

import sys
def input():
	return sys.stdin.readline().strip()

S = input()

alpha = defaultdict(int)
N = len(S)
for i in range(N):
	alpha[S[i]] += 1

num = 0
for n in alpha:
	if alpha[n] % 2 == 1:
		num += 1

if num >= 2:
	print((-1))
	return

alpha_num = defaultdict(deque)
for i in range(N):
	alpha_num[S[i]].append(i)

loc_list = [-1]*N
num = 0
for i in range(N):
	if len(alpha_num[S[i]]) >= 2:
		x = alpha_num[S[i]].popleft()
		y = alpha_num[S[i]].pop()
		loc_list[x] = num
		loc_list[y] = N - 1 - num
		num += 1
	elif len(alpha_num[S[i]]) == 1:
		x = alpha_num[S[i]].popleft()
		loc_list[x] = N // 2

class Bit:
	def __init__(self, n):
		self.size = n
		self.tree = [0] * (n + 1)

	def sum(self, i):
		s = 0
		while i > 0:
			s += self.tree[i]
			i -= i & -i
		return s

	def add(self, i, x):
		while i <= self.size:
			self.tree[i] += x
			i += i & -i

bit = Bit(N)
ans = 0

for i, p in enumerate(loc_list):
	bit.add(p + 1, 1)
	ans += i + 1 - bit.sum(p + 1)

print(ans)


Solve in Python:
You are given a string S constisting of uppercase Latin letters. Is it possible to reorder the characters in this string to get a string with prefix "LTIME" and suffix "EMITL"?
We remind you that a prefix of a string is any substring which contains its first character, while a suffix of a string is substring containing its last character.

-----Input-----
The first line contains a single integer T, denoting the number of testcases. The descriptions of T test cases follow.
The first and only line of the test case description has one non-empty string S consisting of uppercase Latin letters only.

-----Output-----
For each testcase output a single line containing the string "YES" (without quotes) if it's possible to reorder the characters to get the required prefix and suffix, or "NO" (without quotes) otherwise.

-----Constraints-----
- Subtask 1 (23 points) : 1 ≤ T ≤ 100, 1 ≤ |S| ≤ 9
- Subtask 2 (77 points) : 1 ≤ T ≤ 1000, 1 ≤ |S| ≤ 100

-----Example-----
Input:3
LTIMEAZAZAITLME
LLLTTTIIIMMMEEEAHA
LTIMEM

Output:YES
YES
NO

-----Explanation-----
Test case 1: we can permute the last 5 letters and get LTIMEAZAZAEMITL
Test case 2: we have 3 copies of each of the letters 'L', 'T', 'I', 'M', 'E' so we can leave 5 of them in the beginning and move 5 of them to the end.
Test case 3: we have only one letter 'L' so we can't make necessary prefix and suffix at the same time.

# cook your dish here
from collections import Counter
for _ in range(int(input())):

 c=Counter(input())
 #LTIME
 if c['L']>=2 and c['T']>=2 and c['I']>=2 and c['M']>=2 and c['E']>=1:
  print('YES')
 else:
  print('NO')


Solve in Python:
You are given a string S containing only lowercase characters.
You can rearrange the string and you have to print minimum number of characters needed(can be 0) to make it palindrome.

-----Input:-----
- First line contain an interger T denoting number of testcases.
- First line of each testcase contains integer N, size of string.
- Second line of each testcase contains string S.

-----Output:-----
For each test case, print a single line containing one integer ― the minimum number of characters needed(can be 0) to make it palindrome.

-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^5$

-----Sample Input:-----
3
1
a
9
abbbcbddd
6
abcdef

-----Sample Output:-----
0
2
5

-----EXPLANATION:-----
- Example case 1: a is already a palindrome.
- Example case 2: abbddcddbba is palindrome by adding 2 more characters.
- Example case 3: abdefcfedba is palindrome by adding 5 more characters.

try:
    t=int(input())
    for _ in range(t):
        n=int(input())
        s=input()
        i,res=0,0
        dp=[0]*26
        for i in range(n):
            dp[ord(s[i])-97]+=1
        for i in range(26):
            if(dp[i]%2==1):
                res+=1
        if res>0:
            res-=1
        print(res)
except EOFError:
    pass


Solve in Python:
You are given a string S of length N consisting of lowercase English letters.
Process Q queries of the following two types:
 - Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.)
 - Type 2: answer the number of different characters occurring in the substring of S between the l_q-th and r_q-th characters (inclusive).

-----Constraints-----
 - N, Q, i_q, l_q, and r_q are integers.
 - S is a string consisting of lowercase English letters.
 - c_q is a lowercase English letter.
 - 1 \leq N \leq 500000
 - 1 \leq Q \leq 20000
 - |S| = N
 - 1 \leq i_q \leq N
 - 1 \leq l_q \leq r_q \leq N
 - There is at least one query of type 2 in each testcase.

-----Input-----
Input is given from Standard Input in the following format:
N
S
Q
Query_1
\vdots
Query_Q

Here, Query_i in the 4-th through (Q+3)-th lines is one of the following:
1 i_q c_q

2 l_q r_q

-----Output-----
For each query of type 2, print a line containing the answer.

-----Sample Input-----
7
abcdbbd
6
2 3 6
1 5 z
2 1 1
1 4 a
1 7 d
2 1 7

-----Sample Output-----
3
1
5

In the first query, cdbb contains three kinds of letters: b , c , and d, so we print 3.
In the second query, S is modified to abcdzbd.
In the third query, a contains one kind of letter: a, so we print 1.
In the fourth query, S is modified to abcazbd.
In the fifth query, S does not change and is still abcazbd.
In the sixth query, abcazbd contains five kinds of letters: a, b, c, d, and z, so we print 5.

from bisect import bisect_left,bisect_right
import string

dic = {c:[] for c in string.ascii_lowercase}

n = int(input())
s = list(input())
q = int(input())

for i,c in enumerate(s,start=1):
  dic[c].append(i)

for i in range(q):
  p,l,r = list(map(str,input().split()))
  if p =='1':
    j = int(l)
    if r == s[j-1]:
      continue
    c = s[j-1]
    dic[c].pop(bisect_left(dic[c],j))
    dic[r].insert(bisect_left(dic[r],j),j)
    s[j-1] = r
  else:
    ans = 0
    l = int(l)
    r = int(r)
    for c in string.ascii_lowercase:
      pl = bisect_left(dic[c],l)
      if pl < len(dic[c]):
        if dic[c][pl] <= r:
          ans += 1
    print(ans)


Solve in Python:
You are given a string S of length n with each character being one of the first m lowercase English letters.

Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.

Recall that LCS of two strings S and T is the longest string C such that C both in S and T as a subsequence.

-----Input-----

The first line contains two numbers n and m denoting the length of string S and number of first English lowercase characters forming the character set for strings (1 ≤ n ≤ 100 000, 2 ≤ m ≤ 26).

The second line contains string S.

-----Output-----

Print the only line containing the answer.

-----Examples-----
Input
3 3
aaa

Output
6

Input
3 3
aab

Output
11

Input
1 2
a

Output
1

Input
10 9
abacadefgh

Output
789

-----Note-----

For the first sample, the 6 possible strings T are: aab, aac, aba, aca, baa, caa.

For the second sample, the 11 possible strings T are: aaa, aac, aba, abb, abc, aca, acb, baa, bab, caa, cab.

For the third sample, the only possible string T is b.

n, m = map(int, input().split())
s = input()
p = c = 0
for i in range(1, n):
    if s[i] == s[i - 1]:
        c += n * (m - 1)
        p = i
    elif s[i] != s[i - 2]:
        p = i - 1
    c += i - p
ans = n * n * (m - 1) - c
print(ans)


Solve in Python:
You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.
A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.
Return 0 if the string is already balanced.

Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.

Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".

Example 4:
Input: s = "QQQQ"
Output: 3
Explanation: We can replace the last 3 'Q' to make s = "QWER".

Constraints:

1 <= s.length <= 10^5
s.length is a multiple of 4
s contains only 'Q', 'W', 'E' and 'R'.

from sys import maxsize
from collections import Counter
class Solution:
    def balancedString(self, s):
        n = len(s)
        right = 0
        chars = Counter(s)
        res = maxsize
        for left in range(n):
            while right <= n - 1 and any(chars[c] > n // 4 for c in 'QWER'):
                chars[s[right]] -= 1
                right += 1
            if all(chars[c] <= n // 4 for c in 'QWER'):
                res = min(res, right - left)
            chars[s[left]] += 1
        return res


Solve in Python:
You are given a string expression representing a Lisp-like expression to return the integer value of.

The syntax for these expressions is given as follows.

An expression is either an integer, a let-expression, an add-expression, a mult-expression, or an assigned variable.  Expressions always evaluate to a single integer.

(An integer could be positive or negative.)

A let-expression takes the form (let v1 e1 v2 e2 ... vn en expr), where let is always the string "let", then there are 1 or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let-expression is the value of the expression expr.

An add-expression takes the form (add e1 e2) where add is always the string "add", there are always two expressions e1, e2, and this expression evaluates to the addition of the evaluation of e1 and the evaluation of e2.

A mult-expression takes the form (mult e1 e2) where mult is always the string "mult", there are always two expressions e1, e2, and this expression evaluates to the multiplication of the evaluation of e1 and the evaluation of e2.

For the purposes of this question, we will use a smaller subset of variable names.  A variable starts with a lowercase letter, then zero or more lowercase letters or digits.  Additionally for your convenience, the names "add", "let", or "mult" are protected and will never be used as variable names.

Finally, there is the concept of scope.  When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially.  It is guaranteed that every expression is legal.  Please see the examples for more details on scope.

Evaluation Examples:

Input: (add 1 2)
Output: 3

Input: (mult 3 (add 2 3))
Output: 15

Input: (let x 2 (mult x...

class Solution(object):
 	def parse(self,expression,d,i):
 		count = 0
 		start = i
 		if expression[i] == "(":
 			count += 1
 			i += 1
 			while count != 0:
 				if expression[i] == "(":
 					count += 1
 				elif expression[i] == ")":
 					count -= 1
 				i += 1
 			val = self.evaluate(expression[start:i],d)
 		else:
 			while i < len(expression) and expression[i] != " " and expression[i] != ")":
 				i += 1
 			val = expression[start:i]
 			if self.isnumber(val):
 				val = int(val)
 		return i,val
 	def get_left_right(self,expression,d):
 		i = 0
 		count = 0
 		i,left = self.parse(expression,d,0)
 		if i == len(expression) or expression[i] == ")":
 			return left,None,i
 		i += 1
 		i,right = self.parse(expression,d,i)
 		return left,right,i
 	def isnumber(self,s):
 		for c in s:
 			if ord("0") <= ord(c) <= ord("9") or c == "+" or c == "-":
 				continue
 			else:
 				return False
 		return True
 	def evaluate(self, expression,d = {}):
 		"""
 		:type expression: str
 		:rtype: int
 		"""
 		if self.isnumber(expression):
 			return int(expression)
 		newd = {}
 		for key in d:
 			newd[key] = d[key]
 		expression = expression[1:len(expression)-1]
 		oper = ""
 		if expression[0:3] == "add" or expression[:3] == "let":
 			oper = expression[0:3]
 			expression = expression[4:]
 		else:
 			oper = "mult"
 			expression = expression[5:]

 		if oper == "mult" or oper == "add":
 			left,right,_ = self.get_left_right(expression,newd)
 			if isinstance(left,str):
 				left = newd[left]
 			if isinstance(right,str):
 				right = newd[right]
 			if oper == "mult":
 				return left*right
 			else:
 				return left + right
 		i = 0
 		while True:
 			left,right,i = self.get_left_right(expression,newd)
 			expression = expression[i+1:]
 			if right == None:
 				if isinstance(left,str):
 					return newd[left]
 				return left
 			if isinstance(right,str):
 				right = newd[right]
 			newd[left] = right

 # s = Solution()
 # print(s.evaluate("(let x 2 (mult x (let x 3 y 4 (add x y))))"))


Solve in Python:
You are given a string of numbers between 0-9. Find the average of these numbers and return it as a floored whole number (ie: no decimal places) written out as a string. Eg:

"zero nine five two" -> "four"

If the string is empty or includes a number greater than 9, return "n/a"

s2d = "zero one two three four five six seven eight nine".split()

def average_string(stg):
    lst = stg.split()
    if not stg or set(lst) - set(s2d):
        return "n/a"
    return s2d[int(sum(s2d.index(s) for s in lst) / len(lst))]


Solve in Python:
You are given a string of words (x), for each word within the string you need to turn the word 'inside out'. By this I mean the internal letters will move out, and the external letters move toward the centre.

If the word is even length, all letters will move. If the length is odd, you are expected to leave the 'middle' letter of the word where it is.

An example should clarify:

'taxi' would become 'atix'
'taxis' would become 'atxsi'

def swap(word):
    m = len(word) // 2
    if len(word) % 2 == 0:
        return word[:m][::-1] + word[m:][::-1]
    else:
        return word[:m][::-1] + word[m] + word[m+1:][::-1]

def inside_out(st):
    return ' '.join(map(swap, st.split()))


Solve in Python:
You are given a string representing an attendance record for a student. The record only contains the following three characters:

'A' : Absent.
'L' : Late.
 'P' : Present.

A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).

You need to return whether the student could be rewarded according to his attendance record.

Example 1:

Input: "PPALLP"
Output: True

Example 2:

Input: "PPALLL"
Output: False

class Solution:
     def checkRecord(self, s):
         """
         :type s: str
         :rtype: bool
         """
         return s.count("A") < 2 and "LLL" not in s


Solve in Python:
You are given a string s of length 8 consisting solely of '0's and '1's. Assume that the characters of the string are written in a circular fashion. You need to find the number of 0-1 or 1-0 transitions that one has to make while making a single traversal over the string. ie. start from any character and go circularly until you get back to the same character, and find the number of transitions that you made. The string is said to be said to be uniform if there are at most two such transitions. Otherwise, it is called non-uniform.
Given the string s, tell whether the string is uniform or not.

-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of input contains the string s.

-----Output-----
For each test case, output "uniform" if the given string is uniform and "non-uniform" otherwise.

-----Constraints-----
- 1 ≤ T ≤ 256
- Length of s is 8

-----Example-----
Input
4
00000000
10101010
10000001
10010011

Output
uniform
non-uniform
uniform
non-uniform

-----Explanation-----
The number of transitions are 0, 8, 2 and 4 for the respective cases. So, the first and third one are uniform while the second and fourth one are non-uniform.

t=int(input())
for i in range(t):
 n=input()
 co=0
 m=n[0]
 for j in range(1,len(n)):
  if m!=n[j]:
   co+=1
   m=n[j]
  if co>2:
   print("non-uniform")
   break
 if co<=2:
  print("uniform")


Solve in Python:
You are given a string s of length n.
Does a tree with n vertices that satisfies the following conditions exist?
 - The vertices are numbered 1,2,..., n.
 - The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
 - If the i-th character in s is 1, we can have a connected component of size i by removing one edge from the tree.
 - If the i-th character in s is 0, we cannot have a connected component of size i by removing any one edge from the tree.
If such a tree exists, construct one such tree.

-----Constraints-----
 - 2 \leq n \leq 10^5
 - s is a string of length n consisting of 0 and 1.

-----Input-----
Input is given from Standard Input in the following format:
s

-----Output-----
If a tree with n vertices that satisfies the conditions does not exist, print -1.
If a tree with n vertices that satisfies the conditions exist, print n-1 lines.
The i-th line should contain u_i and v_i with a space in between.
If there are multiple trees that satisfy the conditions, any such tree will be accepted.

-----Sample Input-----
1111

-----Sample Output-----
-1

It is impossible to have a connected component of size n after removing one edge from a tree with n vertices.

import sys

s=list(map(int,list(input())))
n=len(s)
if s[0]==0 or s[-1]==1:
    print(-1)
    return
for i in range(n//2):
    if s[i]==s[n-2-i]:
        continue
    else:
        print(-1)
        return
ans=[[1,2]]
last_edge=2
for i in range(3,n+1):
    ans.append([last_edge,i])
    if s[i-2]==1:
        last_edge=i
for u in ans:
    print(*u)


Solve in Python:
You are given a string s that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Your result should not contain any brackets.

Example 1:
Input: s = "(abcd)"
Output: "dcba"

Example 2:
Input: s = "(u(love)i)"
Output: "iloveu"
Explanation: The substring "love" is reversed first, then the whole string is reversed.

Example 3:
Input: s = "(ed(et(oc))el)"
Output: "leetcode"
Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.

Example 4:
Input: s = "a(bcdefghijkl(mno)p)q"
Output: "apmnolkjihgfedcbq"

Constraints:

0 <= s.length <= 2000
s only contains lower case English characters and parentheses.
It's guaranteed that all parentheses are balanced.

class Solution:
    def reverseParentheses(self, s: str) -> str:
        stack = ['']
        for c in s:
            if c == '(':
                stack.append('')
            elif c == ')':
                word = stack.pop()[::-1]
                stack[-1] += word
            else:
                stack[-1] += c
        return ''.join(stack)


Solve in Python:
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to after using the swaps.

Example 1:
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"

Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"

Constraints:

1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s only contains lower case English letters.

from collections import defaultdict

class DisjointSet:
    class Node:
        def __init__(self, x):
            self.val = x
            self.parent = self
            self.rank = 0

    def __init__(self, node_num):
        self.val_to_node = {}

        for val in range(node_num):
            self.val_to_node[val] = DisjointSet.Node(val)

    def find(self, x):
        return self._find(self.val_to_node[x]).val

    def _find(self, node):
        if node.parent is node:
            return node

        node.parent = self._find(node.parent)
        return node.parent

    def union(self, val1, val2):
        root1 = self._find(self.val_to_node[val1])
        root2 = self._find(self.val_to_node[val2])

        if root1 is root2:
            return

        if root2.rank > root1.rank:
            root1, root2 = root2, root1

        if root1.rank == root2.rank:
            root1.rank += 1

        root2.parent = root1

class Solution:
    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
        if not pairs:
            return s

        disjoint_set = DisjointSet(len(s))

        for u, v in pairs:
            disjoint_set.union(u, v)

        connected_components = defaultdict(list)

        for i in range(len(s)):
            connected_components[disjoint_set.find(i)].append(i)

        res = [None] * len(s)
        for group in list(connected_components.values()):
            sorted_chars = sorted([s[i] for i in group])

            for idx, s_i in enumerate(sorted(group)):
                res[s_i] = sorted_chars[idx]

        return ''.join(res)


Solve in Python:
You are given a string s, a split is called good if you can split s into 2 non-empty strings p and q where its concatenation is equal to s and the number of distinct letters in p and q are the same.
Return the number of good splits you can make in s.

Example 1:
Input: s = "aacaba"
Output: 2
Explanation: There are 5 ways to split "aacaba" and 2 of them are good.
("a", "acaba") Left string and right string contains 1 and 3 different letters respectively.
("aa", "caba") Left string and right string contains 1 and 3 different letters respectively.
("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aacab", "a") Left string and right string contains 3 and 1 different letters respectively.

Example 2:
Input: s = "abcd"
Output: 1
Explanation: Split the string as follows ("ab", "cd").

Example 3:
Input: s = "aaaaa"
Output: 4
Explanation: All possible splits are good.
Example 4:
Input: s = "acbadbaada"
Output: 2

Constraints:

s contains only lowercase English letters.
1 <= s.length <= 10^5

class Solution:
    def numSplits(self, s: str) -> int:
        # stores
        unique_chars = {}
        for i, char in enumerate(s):
            if char in unique_chars:
                first, last = unique_chars[char]
                unique_chars[char] = (first, i)
            else:
                unique_chars[char] = (i, i)
        n_unique_chars = len(list(unique_chars.keys()))
        events = []
        for start, end in list(unique_chars.values()):
            events.append((start, 1))
            events.append((end, -1))
        events.sort(key=lambda x: x[0])

        left_num = 0
        right_num = n_unique_chars
        total = 0
        start_good = None
        #print(events)
        for i, event_type in events:
            #print(i, event_type, left_num, right_num)
            if start_good is not None:
                return i - start_good
            if event_type == 1:
                left_num += 1
            else:
                right_num -= 1
            if left_num == right_num:
                start_good = i


Solve in Python:
You are given a string s, consisting of lowercase English letters, and the integer m.

One should choose some symbols from the given string so that any contiguous subsegment of length m has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves.

Then one uses the chosen symbols to form a new string. All symbols from the chosen position should be used, but we are allowed to rearrange them in any order.

Formally, we choose a subsequence of indices 1 ≤ i_1 < i_2 < ... < i_{t} ≤ |s|. The selected sequence must meet the following condition: for every j such that 1 ≤ j ≤ |s| - m + 1, there must be at least one selected index that belongs to the segment [j,  j + m - 1], i.e. there should exist a k from 1 to t, such that j ≤ i_{k} ≤ j + m - 1.

Then we take any permutation p of the selected indices and form a new string s_{i}_{p}_1s_{i}_{p}_2... s_{i}_{p}_{t}.

Find the lexicographically smallest string, that can be obtained using this procedure.

-----Input-----

The first line of the input contains a single integer m (1 ≤ m ≤ 100 000).

The second line contains the string s consisting of lowercase English letters. It is guaranteed that this string is non-empty and its length doesn't exceed 100 000. It is also guaranteed that the number m doesn't exceed the length of the string s.

-----Output-----

Print the single line containing the lexicographically smallest string, that can be obtained using the procedure described above.

-----Examples-----
Input
3
cbabc

Output
a

Input
2
abcab

Output
aab

Input
3
bcabcbaccba

Output
aaabb

-----Note-----

In the first sample, one can choose the subsequence {3} and form a string "a".

In the second sample, one can choose the subsequence {1, 2, 4} (symbols on this positions are 'a', 'b' and 'a') and rearrange the chosen symbols to form a string "aab".

abc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
m = int(input())
string = input()
good = False
toCheck = []
lenS = len(string)
holes = [(-1, lenS)]
have = {'s': 0, 'i': 0, 'y': 0, 'h': 0, 'r': 0, 'f': 0, 'd': 0, 'z': 0, 'q': 0, 't': 0, 'n': 0, 'g': 0, 'l': 0, 'k': 0, 'o': 0, 'c': 0, 'w': 0, 'm': 0, 'b': 0, 'u': 0, 'a': 0, 'v': 0, 'e': 0, 'p': 0, 'j': 0, 'x': 0}
for sym in range(26):
    if not good:
        good = True
        for hole in holes:
            i = hole[0] + 1
            end = hole[1]
            while i < end:
                fill = string[i:min(end, i + m)].rfind(abc[sym])
                if fill == -1:
                    good = False
                    break
                else:
                    have[abc[sym]] += 1
                    i = i + fill + 1
                    if end - i < m:
                        break
            if not good:
                break
        holes = []
    if not good:
        have = {'s': 0, 'i': 0, 'y': 0, 'h': 0, 'r': 0, 'f': 0, 'd': 0, 'z': 0, 'q': 0, 't': 0, 'n': 0, 'g': 0, 'l': 0, 'k': 0, 'o': 0, 'c': 0, 'w': 0, 'm': 0, 'b': 0, 'u': 0, 'a': 0, 'v': 0, 'e': 0, 'p': 0, 'j': 0, 'x': 0}
        toCheck.append(abc[sym])
        good = True
        lastSeen = -1
        for i in range(lenS):
            if string[i] in toCheck:
                have[string[i]] += 1
                if i - lastSeen > m:
                    holes.append((lastSeen, i))
                    good = False
                lastSeen = i
        if lenS - lastSeen > m:
            holes.append((lastSeen, lenS))
            good = False
almost = [have[i] * i for i in abc]
print(''.join(almost))


Solve in Python:
You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.
Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.
Return the string after rearranging the spaces.

Example 1:
Input: text = "  this   is  a sentence "
Output: "this   is   a   sentence"
Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.

Example 2:
Input: text = " practice   makes   perfect"
Output: "practice   makes   perfect "
Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.

Example 3:
Input: text = "hello   world"
Output: "hello   world"

Example 4:
Input: text = "  walks  udp package   into  bar a"
Output: "walks  udp  package  into  bar  a "

Example 5:
Input: text = "a"
Output: "a"

Constraints:

1 <= text.length <= 100
text consists of lowercase English letters and ' '.
text contains at least one word.

class Solution:
    def reorderSpaces(self, text: str) -> str:
        wds = text.split()
        sc = text.count(' ')
        if len(wds) == 1:
            return text.strip(' ')+' '*sc
        nwds = len(wds)
        s = nwds-1
        res = sc//s
        rem = sc-res*s
        ans = ''
        for i in wds[:-1]:
            ans += i
            ans += ' '*res
        ans += wds[-1]
        ans += ' '*rem
        return ans