Solve in Python:
There are n beacons located at distinct positions on a number line. The i-th beacon has position a_{i} and power level b_{i}. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance b_{i} inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.

Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.

-----Input-----

The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons.

The i-th of next n lines contains two integers a_{i} and b_{i} (0 ≤ a_{i} ≤ 1 000 000, 1 ≤ b_{i} ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so a_{i} ≠ a_{j} if i ≠ j.

-----Output-----

Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added.

-----Examples-----
Input
4
1 9
3 1
6 1
7 4

Output
1

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

Output
3

-----Note-----

For the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.

For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42.

n = int(input())
Becone = [list(map(int, input().split())) for i in range(n) ]
Becone.sort( key = lambda x : x[0])
dp = [0]*1000001
#for i in range(1000001) :
#    dp[i] = 0

if Becone[0][0] == 0 :
    dp[0] = 1
    Becone.pop(0)

ans = n - dp[0]
for i in range(1, 1000001) :
    if not Becone :
        break
    if i != Becone[0][0] :
        dp[i] = dp[i-1]
        continue

    a,b = Becone.pop(0)
    if a-b <= 0 :
        dp[i] = 1
    else :
        dp[i] = dp[i-b-1]+1

    ans = min( ans, n - dp[i] )

print( ans )


Solve in Python:
There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

Example:

Input: 3
Output: 1
Explanation:
At first, the three bulbs are [off, off, off].
After first round, the three bulbs are [on, on, on].
After second round, the three bulbs are [on, off, on].
After third round, the three bulbs are [on, off, off].

So you should return 1, because there is only one bulb is on.

class Solution:
     def bulbSwitch(self, n):
         """
         :type n: int
         :rtype: int
         """
         # if n == 0: return 0
         # if n <= 2: return 1
         # cur = 1
         # for i in range(2, int(math.sqrt(n))+1):
         #     a = int(math.sqrt(i))
         #     if a*a == i: cur += 1
         return int(math.sqrt(n))


Solve in Python:
There are n cabs in a city numbered from 1 to n. The city has a rule that only one cab can run in the city at a time. Cab picks up the customer and drops him to his destination. Then the cab gets ready to pick next customer. There are m customers in search of cab. First customer will get the taxi first. You have to find the nearest cab for each customer. If two cabs have same distance then the cab with lower number is preferred.

Your task is to find out minimum distant cab for each customer.

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 test case contains two space-separated integers N and M, denoting the number of cabs and the number of customers.

The next N lines contain two space-separated integers x[i] and y[i], denoting the initial position of the ith cab.

Next line contains an integer M denoting number of customers.
The next M lines contain four space seperated integers sx[i], sy[i], dx[i], dy[i], denoting the current location and the destination of the ith customer.

Output:

Output the nearest cab number for each customer.

Constraints:

1<=t<=10

1<=n,m<=1000

-10^9<=x[i] , y[i] , sx[i] , sy[i] , dx[i] , dy[i]<=10^9

Example:
Input:

1

3 2

1 3

3 2

3 5

2 3 3 4

5 3 4 1

Output:

1

1

Explanation:

The distance of cab1 from customer1 = sqrt((1-2)^2 + (3-3)^2) = 1

The distance of cab2 from customer1 = sqrt(2)

The distance of cab3 from customer1 = sqrt(5)

So output for customer1 is 1

Now location of cab1 is (3,4)

The distance of cab1 from customer2 = sqrt((3-5)^2 + (4-3)^2) = sqrt(5)

The distance of cab2 from customer2 = sqrt(5)

The distance of cab3 from customer2 = sqrt(8)

So output for customer2 is 1

import math
def dist(w,x,y,z):
 return math.hypot(y - w, z - x)

t = int(input())
while (t>0):
 t = t -1
 n, m = list(map(int,input().split()))
 a = []
 for i in range(0,n):
  x,y = list(map(int,input().split()))
  a.append([x,y])
 for j in range(0,m):
  p,q,r,s = list(map(int,input().split()))
  nearest = -1
  distance = 10000000000
  for i in range(0,n):
   way = dist(a[i][0],a[i][1],p,q)
   if way < distance:
    distance = way
    nearest = i
  print(nearest + 1)
  a[nearest][0] = r
  a[nearest][1] = s


Solve in Python:
There are n cards of different colours placed in a line, each of them can be either red, green or blue cards. Count the minimum number of cards to withdraw from the line so that no two adjacent cards have the same colour.

-----Input-----
- The first line of each input contains an integer n— the total number of cards.
- The next line of the input contains a string s, which represents the colours of the cards. We'll consider the cards in a line numbered from 1 to n from left to right. Then the $i^t$$^h$ alphabet equals "G", if the $i^t$$^h$ card is green, "R" if the card is red,  and "B", if it's blue.

-----Output-----
- Print a single integer — the answer to the problem.

-----Constraints-----
- $1 \leq n \leq 50$

-----Sample Input 1:-----
5
RGGBG

-----Sample Input 2:-----
5
RRRRR

-----Sample Input 3:-----
2
BB

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

-----Sample Output 2:-----
4

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

# cook your dish here
n=int(input())
s=input()
l=[]
for i in s:
    l.append(i)
ans=0
for i in range(1,len(s)):
    if l[i-1]==l[i]:
        ans+=1
print(ans)


Solve in Python:
There are n chef's in Chefland. There is a festival in Chefland in which each chef is asked to vote a person as his best friend. Obviously, a person can't vote himself as his best friend.  Note that the best friend relationship is not necessarily bi-directional, i.e. it might be possible that x is best friend of y, but y is not a best friend of x.

Devu was the election commissioner who conducted this voting. Unfortunately, he was sleeping during the voting time. So, he could not see the actual vote of each person, instead after the voting, he counted the number of votes of each person and found that number of votes of i-th person was equal to ci.

Now he is wondering whether this distribution of votes corresponds to some actual voting or some fraudulent voting has happened. If the current distribution of votes does not correspond to any real voting, print -1. Otherwise, print any one of the possible voting which might have lead to the current distribution. If there are more than one possible ways of voting leading to the current distribution, you can print any one of them.

-----Input-----
- First line of the input contains a single integer T denoting number of test cases.
- First line of each test case, contains a single integer n.
- Second line of each test case, contains n space separated integers denoting array c.

-----Output-----
For each test case,

- If there is no real voting corresponding to given distribution of votes, print -1 in a single line.
- Otherwise, print n space separated integers denoting a possible voting leading to current distribution of votes. i-th integer should denote the index of the person (1 based indexing) whom i-th person has voted as his best friend.

-----Constraints and Subtasks-----
- 1 ≤ T ≤ 500
- 1 ≤ n ≤ 50
- 0 ≤ ci ≤ n

-----Example-----
Input:
3
3
1 1 1
3
3 0 0
3
2 2 0

Output:
2 3 1
-1
-1

-----Explanation-----
Example 1: In this example, each person has received one vote. One possible example of real voting leading to this distribution is {2, 3, 1}. In this...

t=int(input())
for _ in range(t):
 n=int(input())
 l=list(map(int,input().split()))
 if sum(l)!=n or max(l)==n:
  print('-1')
 else:
  ans=[]
  for i in range(n):
   for j in range(l[i]):
    ans.append(i+1)
  #final_ans=[-1]*n
  for i in range(len(ans)):
   if ans[i]==i+1:

    for j in range(len(ans)):
     if ans[j]!=i+1 :
      ans[i],ans[j]=ans[j],ans[i]
      break
  print(*ans)


Solve in Python:
There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w.

Now given all the cities and fights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.

Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph looks like this:

The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.

Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph looks like this:

The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.

Note:

       The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1.
       The size of flights will be in range [0, n * (n - 1) / 2].
       The format of each flight will be (src, dst, price).
       The price of each flight will be in the range [1, 10000].
       k is in the range of [0, n - 1].
       There will not be any duplicated flights or self cycles.

from functools import reduce
 from collections import deque
 class Solution:
     def slidingPuzzle(self, board):
         """
         :type board: List[List[int]]
         :rtype: int
         """
         hashtable = {}
         end, steps = "123450", None
         startstr = ''.join([str(i) for i in board[0]]) + ''.join([str(i) for i in board[1]])
         options = [[1,3],[0,2,4],[1,5],[0,4],[1,3,5],[2,4]]
         queue = deque()
         queue.append([startstr, 0])

         def move(currstr, moveto, currenti):
             moving = currstr[moveto]
             currstr = currstr.replace(moving, '!',)
             currstr = currstr.replace('0', moving)
             currstr = currstr.replace('!', '0')
             return currstr

         while (len(queue) > 0 and steps == None):
             currstr = queue.popleft()
             if currstr[0] == end:
                 steps = currstr[1]
                 break

             if currstr[0] not in hashtable:
                 currenti = currstr[0].find('0')
                 hashtable[currstr[0]] = True
                 possibilities = [move(currstr[0], i, currenti) for i in options[currenti]]
                 for el in possibilities:
                     queue.append([el, currstr[1] + 1])

         return -1 if steps == None else steps


Solve in Python:
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.
Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.
Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.

Example 1:

Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Output: 3
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 4 for each city are:
City 0 -> [City 1, City 2]
City 1 -> [City 0, City 2, City 3]
City 2 -> [City 0, City 1, City 3]
City 3 -> [City 1, City 2]
Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.

Example 2:

Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
Output: 0
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 2 for each city are:
City 0 -> [City 1]
City 1 -> [City 0, City 4]
City 2 -> [City 3, City 4]
City 3 -> [City 2, City 4]
City 4 -> [City 1, City 2, City 3]
The city 0 has 1 neighboring city at a distanceThreshold = 2.

Constraints:

2 <= n <= 100
1 <= edges.length <= n * (n - 1) / 2
edges[i].length == 3
0 <= fromi < toi < n
1 <= weighti, distanceThreshold <= 10^4
All pairs (fromi, toi) are distinct.

class Solution:
    def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
        def BFS(queue):
            while queue:
                route , wt = queue.popleft()
                for node , node_wt in d[route]:
                    if min_wt[node] > node_wt + wt:
                        queue.append([node , node_wt + wt])
                        min_wt[node] = node_wt + wt
            return min_wt
        d , seen ,ans , m = defaultdict(list) , set()  , [] , inf
        for x , y , z in edges:d[x] += [[y,z]];d[y] += [[x,z]]
        for i in range(n):
            min_wt = [inf]*(n)
            ans.append(BFS(deque([[i,0]])))
            min_wt[i] = inf
        res = 0
        for q,i in enumerate(ans):
            count = 0
            for j in i:
                if j <= distanceThreshold:count += 1
            if count <= m :res = q;m = count
        return res


Solve in Python:
There are n engineers numbered from 1 to n and two arrays: speed and efficiency, where speed[i] and efficiency[i] represent the speed and efficiency for the i-th engineer respectively. Return the maximum performance of a team composed of at most k engineers, since the answer can be a huge number, return this modulo 10^9 + 7.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.

Example 1:
Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2
Output: 60
Explanation:
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.

Example 2:
Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3
Output: 68
Explanation:
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.

Example 3:
Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4
Output: 72

Constraints:

1 <= n <= 10^5
speed.length == n
efficiency.length == n
1 <= speed[i] <= 10^5
1 <= efficiency[i] <= 10^8
1 <= k <= n

class Solution:
    def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
        items = sorted(zip(speed, efficiency), key=lambda item: (-item[1], -item[0]))
        heap = []

        s = 0
        res = 0

        for item in items:
            if len(heap) < k or item[0] > heap[0][0]:
                if len(heap) == k:
                    popped = heapq.heappop(heap)
                    s -= popped[0]
                heapq.heappush(heap, item)
                s += item[0]
                res = max(res, s * item[1])

        return res % (10 ** 9 + 7)


Solve in Python:
There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played.

You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d_1 and that of between second and third team will be d_2.

You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?

Note that outcome of a match can not be a draw, it has to be either win or loss.

-----Input-----

The first line of the input contains a single integer corresponding to number of test cases t (1 ≤ t ≤ 10^5).

Each of the next t lines will contain four space-separated integers n, k, d_1, d_2 (1 ≤ n ≤ 10^12; 0 ≤ k ≤ n; 0 ≤ d_1, d_2 ≤ k) — data for the current test case.

-----Output-----

For each test case, output a single line containing either "yes" if it is possible to have no winner of tournament, or "no" otherwise (without quotes).

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

Output
yes
yes
yes
no
no

-----Note-----

Sample 1. There has not been any match up to now (k = 0, d_1 = 0, d_2 = 0). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.

Sample 2. You missed all the games (k = 3). As d_1 = 0 and d_2 = 0, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is "yes".

Sample 3. You missed 4 matches, and d_1 = 1, d_2 = 0. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2...


Solve in Python:
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.

Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.

The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.

-----Input-----

The first line contains a single integer — n (1 ≤ n ≤ 5·10^5). Each of the next n lines contains an integer s_{i} — the size of the i-th kangaroo (1 ≤ s_{i} ≤ 10^5).

-----Output-----

Output a single integer — the optimal number of visible kangaroos.

-----Examples-----
Input
8
2
5
7
6
9
8
4
2

Output
5

Input
8
9
1
6
2
6
5
8
3

Output
5

import sys
import math
n = int(input())
k = sorted(int(x) for x in sys.stdin)
p1 = (n//2)-1
p2 = n-1
count = 0
while p2>(n//2-1) and p1>=0:
    if (k[p1]*2<=k[p2]):
        p2-=1
        count+=1
    p1-=1
print(n-count)


Solve in Python:
There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:

Eat one orange.
If the number of remaining oranges (n) is divisible by 2 then you can eat  n/2 oranges.
If the number of remaining oranges (n) is divisible by 3 then you can eat  2*(n/3) oranges.

You can only choose one of the actions per day.
Return the minimum number of days to eat n oranges.

Example 1:
Input: n = 10
Output: 4
Explanation: You have 10 oranges.
Day 1: Eat 1 orange,  10 - 1 = 9.
Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)
Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1.
Day 4: Eat the last orange  1 - 1  = 0.
You need at least 4 days to eat the 10 oranges.

Example 2:
Input: n = 6
Output: 3
Explanation: You have 6 oranges.
Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).
Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)
Day 3: Eat the last orange  1 - 1  = 0.
You need at least 3 days to eat the 6 oranges.

Example 3:
Input: n = 1
Output: 1

Example 4:
Input: n = 56
Output: 6

Constraints:

1 <= n <= 2*10^9

class Solution:
    def minDays(self, n: int) -> int:
        ONE_LIMIT = 100
        TWO_LIMIT = 30
        f = {1:1}
        def search(n, one, two):
            # if n == 1 return 1
            if one > ONE_LIMIT:
                return 1000
            if two > TWO_LIMIT:
                return 1000
            if n in f:
                return f[n]
            ans = 1000
            if n % 3 == 0:
                ans = min(ans, search(n//3, one, two))
            if n % 2 == 0:
                ans = min(ans, search(n//2, one, two + 1))
            ans = min(ans, search(n-1, one+1, two))
            f[n] = 1 + ans
            return f[n]

        search(n,0,0)

        return f[n]


Solve in Python:
There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.
Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.

Example 1:

Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
Output: ["B","C"]
Explanation:
You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):
Person with id = 1 -> watchedVideos = ["C"]
Person with id = 2 -> watchedVideos = ["B","C"]
The frequencies of watchedVideos by your friends are:
B -> 1
C -> 2

Example 2:

Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
Output: ["D"]
Explanation:
You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).

Constraints:

n == watchedVideos.length == friends.length
2 <= n <= 100
1 <= watchedVideos[i].length <= 100
1 <= watchedVideos[i][j].length <= 8
0 <= friends[i].length < n
0 <= friends[i][j] < n
0 <= id < n
1 <= level < n
if friends[i] contains j, then friends[j] contains i

class Solution:
    def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:
        g_friends = collections.defaultdict(list)
        for i in range(len(friends)):
            for f in friends[i]:
                g_friends[i].append(f)
        queue = collections.deque()
        queue.append((id, 0))
        visited = set([id])
        videos = collections.defaultdict(int)
        while queue:
            size = len(queue)
            for _ in range(size):
                curr_id, curr_level = queue.popleft()
                if curr_level == level:
                    for v in watchedVideos[curr_id]:
                        videos[v] += 1
                else:
                    for f in g_friends[curr_id]:
                        if f not in visited:
                            visited.add(f)
                            queue.append((f, curr_level + 1))

        return [v for _, v in sorted([(f, v) for v, f in list(videos.items())])]


Solve in Python:
There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.
Return a list of groups such that each person i is in a group of size groupSizes[i].
Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.

Example 1:
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
The first group is [5]. The size is 1, and groupSizes[5] = 1.
The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.
The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].

Example 2:
Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]

Constraints:

groupSizes.length == n
1 <= n <= 500
1 <= groupSizes[i] <= n

class Solution:
    def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
        groups = {}
        output = []

        for i in range(len(groupSizes)):
            belongGroupCount = groupSizes[i]
            # print(f'group: {belongGroupCount} | person i: {i}')

            existingGroup = groups.get(belongGroupCount)
            # print(f'existing: {groups}, belong: {belongGroupCount}')
            if existingGroup is None:
                groups[belongGroupCount] = []
                existingGroup = groups.get(belongGroupCount)

            existingGroup.append(i)
            if len(existingGroup) == belongGroupCount:
                output.append(existingGroup)
                groups[belongGroupCount] = []
            else:
                groups[belongGroupCount] = existingGroup

        return output


Solve in Python:
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.

You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.

-----Input-----

The first line of input contains integer n denoting the number of psychos, (1 ≤ n ≤ 10^5). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive — ids of the psychos in the line from left to right.

-----Output-----

Print the number of steps, so that the line remains the same afterward.

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

Output
2

Input
6
1 2 3 4 5 6

Output
0

-----Note-----

In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1]  →  [10 8 4]  →  [10]. So, there are two steps.

from math import sqrt,ceil,gcd
from collections import defaultdict

def modInverse(b,m):
    g = gcd(b, m)
    if (g != 1):
        # print("Inverse doesn't exist")
        return -1
    else:
        # If b and m are relatively prime,
        # then modulo inverse is b^(m-2) mode m
        return pow(b, m - 2, m)

def sol(n,m,rep):

    r = 1
    for i in range(2,n+1):
        j = i
        while j%2 == 0 and rep>0:

            j//=2
            rep-=1

        r*=j
        r%=m

    return r

def solve():

   n = int(input())
   l = list(map(int,input().split()))
   st = []
   ans = 0
   hash = defaultdict(lambda : -1)
   for i in range(n):
       hash[i] = 0

       while st!=[] and l[st[-1]]<l[i]:
               z = st.pop()
               hash[i] = max(hash[i],hash[z]+1)

       if st == []:
           hash[i] = -1
       st.append(i)
       ans = max(ans,hash[i]+1)
   print(ans)

# t = int(input())
# for _ in range(t):
solve()


Solve in Python:
There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes.

The schedule on Monday is known for each group, i. e. time slots when group will have classes are known.

Your task is to determine the minimum number of rooms needed to hold classes for all groups on Monday. Note that one room can hold at most one group class in a single time slot.

-----Input-----

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of groups.

Each of the following n lines contains a sequence consisting of 7 zeroes and ones — the schedule of classes on Monday for a group. If the symbol in a position equals to 1 then the group has class in the corresponding time slot. In the other case, the group has no class in the corresponding time slot.

-----Output-----

Print minimum number of rooms needed to hold all groups classes on Monday.

-----Examples-----
Input
2
0101010
1010101

Output
1

Input
3
0101011
0011001
0110111

Output
3

-----Note-----

In the first example one room is enough. It will be occupied in each of the seven time slot by the first group or by the second group.

In the second example three rooms is enough, because in the seventh time slot all three groups have classes.

grp = int(input())
tab = [""] * grp
for _ in range(grp):
  tab[_] = input()
m = 0
for i in range(7):
  t = 0
  for seq in tab:
    t+=int(seq[i])
  if t > m:
    m = t
  if t == grp:
    break
print(m)


Solve in Python:
There are n villages in a Chefland. Some of the villages have electricity facilities, other doesn't. You can consider the villages arranged in line in the order 1 to n from left to right. i-th of village can be considered at xi coordinates.

Chef decided that electricity should be provided to all the villages. So, he decides to buy some amount of electric wires to connect the villeges without electricity to some villages with electricity. As Chef does not want to spend too much amount of money on wires, can you find out minimum amount of length of wire Chef should buy.

-----Input-----
First line of the input contains an integer T denoting the number of test cases. T test cases follow.
First line of each test case contains an integer n denoting number of villages in Chefland.
Second line will contain a string of length n containing '0' or '1's only. If i-th character of the string is '1', then it denotes that i-th village has electricity.
Next line contains n space separated integers denoting the x coordinates of the villages in the order from village 1 to n

-----Output-----
For each test case, output a single line containing a integer corresponding to the minimum length of wire Chef needs to buy.

-----Constraints-----
- 1 ≤ T ≤ 10
- It is guaranteed that there will be at least one village which will have electricity.
- 1 ≤ x1 <  x2 <  ... < xn ≤ 109

-----Subtasks-----
Subtask #1 : 30 points
- 1 ≤ N ≤ 1000

Subtask #2 : 70 points
- 1 ≤ N ≤ 105

-----Example-----
Input
2
2
01
1 2
3
100
1 5 6
Output:
1
5

-----Explanation-----
In the first example, first village does not have electricity. If we put a wire between village 1 and 2 of length 1, then both the villages will have electricity.

In the second example,
We can a draw a wire from first village to third village, passing through second village. Its total length will be 5. Now all the villages will have electricity. This is the minimum length of wire you will require.


Solve in Python:
There are players standing in a row each player has a digit written on their T-Shirt (multiple players can have the same number written on their T-Shirt).
You have to select a group of players, note that players in this group should be standing in $\textbf{consecutive fashion}$. For example second player of chosen group next to first player of chosen group, third player next to second and similarly last player next to second last player of chosen group. Basically You've to choose a contiguous group of players.
After choosing a group, players can be paired if they have the same T-Shirt number (one player can be present in at most one pair), finally the chosen group is called “good” if at most one player is left unmatched. Your task is to find the size of the maximum “good” group.
Formally, you are given a string $S=s_{1}s_{2}s_{3}...s_{i}...s_{n}$ where $s_{i}$ can be any digit character between $'0'$ and $'9'$ and $s_{i}$ denotes the number written on the T-Shirt of $i^{th}$ player. Find a value $length$ such that there exist pair of indices $(i,j)$ which denotes $S[i...j]$ is a “good” group where $i\geq1$ and $j\leq S.length$ and $i\leq j$ and $(j-i+1)=length$ and there exist no other pair $(i’,j’)$ such that $(j’-i’+1)>length$ and $S[i'...j']$ is a "good" group.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- $i^{th}$ testcase consist of a single line of input, a string $S$.

-----Output:-----
For each testcase, output in a single line maximum possible size of a "good" group.

-----Constraints-----
$\textbf{Subtask 1} (20 points)$
- $1 \leq T \leq 10$
- $S.length \leq 10^{3}$
$\textbf{Subtask 2} (80 points)$
- $1 \leq T \leq 10$
- $S.length \leq 10^{5}$

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

123343

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

-----EXPLANATION:-----
1$\textbf{$\underline{2 3 3}$}$43
Underlined group is a “good” group because the second player(number 2 on T-Shirt) is the only player who is left unmatched and third and fourth player can form a pair, no other group...

import sys
import math
from collections import defaultdict,Counter

# input=sys.stdin.readline
# def print(x):
#     sys.stdout.write(str(x)+"\n")

# sys.stdout=open("CP1/output.txt",'w')
# sys.stdin=open("CP1/input.txt",'r')

def possible(n1,n):
	# d=defaultdict(int)
	odd=set()
	# even=set()
	for j in range(n):
		# print(odd)
		if s[j] in odd:
			odd.remove(s[j])
			# even.add(s[j])
		else:
			odd.add(s[j])
		# d[s[j]]+=1
		# print(odd)
		if j<n1-1:
			continue
		# print(j)
		if len(odd)<=1:
			return True

		if s[j-n1+1] in odd:
			odd.remove(s[j-n1+1])
			# even.add(s[j])
		else:
			odd.add(s[j-n1+1])
	return False
# m=pow(10,9)+7
t=int(input())
for i in range(t):
	s=list(input())
	n=len(s)
	ans=1
	for j in range(n,1,-1):
		if possible(j,n):
			ans=j
			break
	print(ans)
	# low=1
	# high=n
	# while low<=high:
	# 	mid=(low+high)//2
	# 	if mid%2==0:
	# 		if low%2==0:
	# 			low+=1
	# 			mid+=1
	# 		elif high%2==0:
	# 			high-=1
	# 			mid-=1
	# 	# if low>high:
	# 	# 	break
	# 	if possible(mid,n):
	# 		low=mid+1
	# 	else:
	# 		high=mid-1
	# 	print(mid,low,high)
	# print(mid)


Solve in Python:
There are several (or no) spiders, butterflies, and dragonflies.

In this kata, a spider has eight legs. A dragonfly or a butterfly has six legs. A __dragonfly__ has __two__ pairs of wings, while a __butterfly__ has __one__ pair of wings. __I am not sure whether they are biologically correct, but the values apply here. __

Given the number of total heads, legs, and __pairs of__ wings, please calculate numbers of each kind of bugs. Of course they are integers.
_However, I do not guarantee that they are positive in the test cases.
Please regard the minus numbers as cases that does not make sense. _

If answers make sense, return [n\_spider, n\_butterfly, n\_dragonfly];
else, please return [-1, -1, -1].

Example:

cal\_n\_bug(3, 20, 3) = [1, 1, 1]
One spider, one butterfly, one dragonfly in total have three heads, twenty legs (8 for the spider, 6 for the butterfly, and 6 for the dragonfly), and _three pairs_ of wings (1 for the butterfly and 2 for the dragonfly).

def cal_n_bug(n_head, n_leg, n_wing):
    if n_head<0 or n_leg<0 or n_wing<0:
        return [-1,-1,-1]
    x=n_leg-6*n_head
    y=8*n_head-n_leg-n_wing
    z=n_leg+2*n_wing-8*n_head
    if x%2!=0 or z%2!=0 or x<0 or y<0 or z<0:
        return [-1,-1,-1]
    return [x//2,y,z//2]


Solve in Python:
There are several cards arranged in a row, and each card has an associated number of points The points are given in the integer array cardPoints.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array cardPoints and the integer k, return the maximum score you can obtain.

Example 1:
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.

Example 2:
Input: cardPoints = [2,2,2], k = 2
Output: 4
Explanation: Regardless of which two cards you take, your score will always be 4.

Example 3:
Input: cardPoints = [9,7,7,9,7,7,9], k = 7
Output: 55
Explanation: You have to take all the cards. Your score is the sum of points of all cards.

Example 4:
Input: cardPoints = [1,1000,1], k = 1
Output: 1
Explanation: You cannot take the card in the middle. Your best score is 1.

Example 5:
Input: cardPoints = [1,79,80,1,1,1,200,1], k = 3
Output: 202

Constraints:

1 <= cardPoints.length <= 10^5
1 <= cardPoints[i] <= 10^4
1 <= k <= cardPoints.length

class Solution:
    def maxScore(self, cardPoints: List[int], k: int) -> int:
        right_index = len(cardPoints)-k
        curr_max = sum(cardPoints[right_index:])
        curr_sum = curr_max
        for left_index in range(0, k):
            curr_sum -= cardPoints[right_index]
            right_index += 1
            curr_sum += cardPoints[left_index]
            if curr_sum > curr_max:
                curr_max = curr_sum
        return curr_max


Solve in Python:
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.

For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.

The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.

There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?

Formally, we assume that two words denote the same name, if using the replacements "u" [Image] "oo" and "h" [Image] "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.

For example, the following pairs of words denote the same name:  "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" $\rightarrow$ "kuuper" and "kuooper" $\rightarrow$ "kuuper".  "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" $\rightarrow$ "khoon" and "kkkhoon" $\rightarrow$ "kkhoon" $\rightarrow$ "khoon".

For a given list of words, find the minimal number of groups where the words in each group denote the same name.

-----Input-----

The first line contains integer number n (2 ≤ n ≤ 400) — number of the words in the list.

The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.

-----Output-----

Print the minimal number of groups where the words in each group denote the same...

c=[]
n=int(input())
for uygf in range(n):
    s=list(input())
    l=len(s)
    i=0
    p=[]
    d=['u','o','k','h']
    while(i<l):
        if(s[i] not in d):
            p.append(s[i])
            i+=1
        elif(s[i]=='o'):
            if(i+1<l and s[i+1]=='o'):
                p.append('u')
                i+=2
            elif(i+1<l and s[i+1]=='u'):
                p.append('u')
                s[i+1]='o'
                i+=1
            else:
                p.append('o')
                i+=1
        elif(s[i]=='k'):
            y=i+1
            while(y<l and s[y]=='k'):
                y+=1
            if(y!=l):
                if(s[y]=='h'):

                    p.append('h')
                    i=y+1
                else:
                    for pp in range(i,y):
                        p.append('k')
                    i=y
            else:
                for pp in range(i,y):
                    p.append('k')
                i=y
        else:
            p.append(s[i])
            i+=1

    c.append(p)
d=[]
for i in range(n):
    if(i in d):
        continue
    for j in range(i+1,n):
        if(c[i]==c[j]):
            d.append(j)
print(n-len(d))


Solve in Python:
There are some candies that need to be distributed to some children as fairly as possible (i.e. the variance of result needs to be as small as possible), but I don't know how to distribute them, so I need your help. Your assignment is to write a function with signature `distribute(m, n)` in which `m` represents how many candies there are, while `n` represents how many children there are. The function should return a container which includes the number of candies each child gains.

# Notice
1. *The candy can't be divided into pieces.*
2. The list's order doesn't matter.

# Requirements
1. The case `m < 0` is equivalent to `m == 0`.
2. If `n <= 0` the function should return an empty container.
3. If there isn't enough candy to distribute, you should fill the corresponding number with `0`.

# Examples
```python
distribute(-5,  0) # should be []
distribute( 0,  0) # should be []
distribute( 5,  0) # should be []
distribute(10,  0) # should be []
distribute(15,  0) # should be []
distribute(-5, -5) # should be []
distribute( 0, -5) # should be []
distribute( 5, -5) # should be []
distribute(10, -5) # should be []
distribute(15, -5) # should be []
distribute(-5, 10) # should be [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
distribute( 0, 10) # should be [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
distribute( 5, 10) # should be [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
distribute(10, 10) # should be [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
distribute(15, 10) # should be [2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
```

# Input
  1. m: Integer (m <= 100000)
  2. n: Integer (n <= 1000)

# Output
  1. [Integer]

def distribute(m, n):
    q, r = divmod(max(m, 0), max(n, 1))
    return [q + (i < r) for i in range(max(n, 0))]


Solve in Python:
There are some perfect squares with a particular property.
For example the number ```n = 256``` is a perfect square, its square root is ```16```. If we change the position of the digits of n, we may obtain another perfect square``` 625``` (square root = 25).
With these three digits ```2```,```5``` and ```6``` we can get two perfect squares: ```[256,625]```

The number ```1354896``` may generate another ```4``` perfect squares, having with the number itself, a total of five perfect squares: ```[1354896, 3594816, 3481956, 5391684, 6395841]```, being the last one in the list, ```6395841```, the highest value of the set.

Your task is to find the first perfect square above the given lower_limit, that can generate the given k number of perfect squares, and it doesn't contain the digit 0. Then return the maximum perfect square that can be obtained from its digits.

Example with the cases seen above:
```
lower_limit = 200
k = 2 (amount of perfect squares)
result = 625

lower_limit = 3550000
k = 5 (amount of perfect squares)
result  = 6395841
```
Features of the random tests:
```
100 <= lower_limit <= 1e6
2 <= k <= 5
number of tests = 45
```
Have a good time!

import itertools
def next_perfectsq_perm(l, k):
    perf = lambda n: n**0.5%1 == 0
    while True:
        l += 1
        if perf(l) and '0' not in str(l):
            r = [x for x in set([int(''.join(x)) for x in list(itertools.permutations(str(l)))]) if perf(x)]
            if len(r) == k: return max(r)


Solve in Python:
There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought $n$ carrots with lengths $a_1, a_2, a_3, \ldots, a_n$. However, rabbits are very fertile and multiply very quickly. Zookeeper now has $k$ rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into $k$ pieces. For some reason, all resulting carrot lengths must be positive integers.

Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size $x$ is $x^2$.

Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots.

-----Input-----

The first line contains two integers $n$ and $k$ $(1 \leq n \leq k \leq 10^5)$: the initial number of carrots and the number of rabbits.

The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ $(1 \leq a_i \leq 10^6)$: lengths of carrots.

It is guaranteed that the sum of $a_i$ is at least $k$.

-----Output-----

Output one integer: the minimum sum of time taken for rabbits to eat carrots.

-----Examples-----
Input
3 6
5 3 1

Output
15

Input
1 4
19

Output
91

-----Note-----

For the first test, the optimal sizes of carrots are $\{1,1,1,2,2,2\}$. The time taken is $1^2+1^2+1^2+2^2+2^2+2^2=15$

For the second test, the optimal sizes of carrots are $\{4,5,5,5\}$. The time taken is $4^2+5^2+5^2+5^2=91$.

def calc(l, n):
    smol = l // n
    tol = l % n
    return smol * smol * n + (2 * smol + 1) * tol

import heapq
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
curr = [1] * n

q = []
for i in range(n):
    v = a[i]
    heapq.heappush(q, (calc(v, 2) - calc(v, 1), i))

out2 = sum([x*x for x in a])

for i in range(k - n):
    diff, nex = heapq.heappop(q)
    curr[nex] += 1
    v = a[nex]
    heapq.heappush(q, (calc(v, curr[nex] + 1) - calc(v, curr[nex]), nex))
    out2 += diff

out = 0
for i in range(n):
    out += calc(a[i], curr[i])
assert(out == out2)
print(out)


Solve in Python:
There are some stones on Bob's table in a row, and each of them can be red, green or blue, indicated by the characters `R`, `G`, and `B`.

Help Bob find the minimum number of stones he needs to remove from the table so that the stones in each pair of adjacent stones have different colours.

Examples:

```
"RGBRGBRGGB"   => 1
"RGGRGBBRGRR"  => 3
"RRRRGGGGBBBB" => 9
```

def solution(s):
    r = s
    for i in range(9):
        r = r.replace('RR', 'R').replace('GG', 'G').replace('BB', 'B')

    return len(s) - len(r)


Solve in Python:
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.

You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where:

  <hostname> — server name (consists of words and maybe some dots separating them),  /<path> — optional part, where <path> consists of words separated by slashes.

We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa — for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications.

Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.

Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different.

-----Input-----

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where:

  <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20.  <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20.

Addresses are not guaranteed to be distinct.

-----Output-----

First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one.

Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are...

n=int(input())
d={}
D={}
for i in range(n):
    h,*p=(input()[7:]+'/').split('/')
    d.setdefault(h,set()).add('/'.join(p))
for x in d:
    t=tuple(sorted(d[x]))
    D.setdefault(t,[]).append(x)

def ans():
    for x in D:
        if len(D[x])>1:
            yield 'http://'+' http://'.join(D[x])

print(sum(1 for x in D if len(D[x])>1))
print('\n'.join(ans()))


Solve in Python:
There are three squares, each with side length a placed on the x-axis. The coordinates of centers of these squares are (x1, a/2), (x2, a/2) and (x3, a/2) respectively. All of them are placed with one of their sides resting on the x-axis.
You are allowed to move the centers of each of these squares along the x-axis (either to the left or to the right)  by a distance of at most K. Find the maximum possible area of intersections of all these three squares that you can achieve. That is, the maximum area of the region which is part of all the three squares in the final configuration.

-----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 a, K denoting side length of the squares, and the maximum distance that you can move the center of any square.
- The second line contains three space separated integers x1, x2, x3

-----Output-----
For each test case, output a real number corresponding to the maximum area of the intersection of the three squares that you can obtain. Your answer will be considered correct if it has an absolute error of less than or equal to 	10-2.

-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ a ≤ 105
- 0 ≤ K ≤ 106
- -106 ≤ x1, x2, x3 ≤ 106

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

Output
0.000000
1.0000
0.0

-----Explanation-----
Testcase 1: The figure below shows the three squares:

Since K = 0, they cannot be moved, and since there is no region which belongs to all three squares, the answer is 0.
Testcase 2: The starting configuration is the same as above, but now each of the squares can move 1 unit. So we can move the first square 1 unit to the right and the third square one unit to the left, and have all the three squares at x-coordinate = 2. Thus the entire square is part of all three squares, and the answer is 1.

for _ in range(int(input())):
 a,k = list(map(int,input().split()))
 l = list(map(int,input().split()))
 l.sort()
 ans = 0

 s = l[0]-a/2-k
 e = l[0]+a/2+k

 s = max(s,l[1]-a/2-k)
 e = min(e,l[1]+a/2+k)

 s = max(s,l[2]-a/2-k)
 e = min(e,l[2]+a/2+k)

 if s<e:
  ans = min(e-s,a)*a

 print(ans)


Solve in Python:
There are total $N$ cars in a sequence with $ith$ car being assigned with an alphabet equivalent to the $ith$ alphabet of string $S$ . Chef has been assigned a task to calculate the total number of cars with alphabet having a unique even value in the given range X to Y (both inclusive)
. The value of an alphabet is simply its position in alphabetical order e.g.: a=1, b=2, c=3…
The chef will be given $Q$
such tasks having varying values of $X$ and $Y$
Note: string $S$ contains only lowercase alphabets

-----Input-----
First line of input contains a string $S$ of length $N$.
Second line contains an integer denoting no. of queries $Q$.
Next q lines contain two integers denoting values of $X$ and $Y$.

-----Output-----
For each query print a single integer denoting total number of cars with alphabet having a unique even value in the given range $X$ to $Y$.

-----Constraints-----
- $1 \leq n \leq 10^5$
- $1 \leq q \leq 10^5$

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

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

-----Explanation:-----
Example case 1:
Query 1: range 1 to 2 contains the substring $"bb"$ where each character has a value of 2. Since we will only be considering unique even values, the output will be 1

string = input()
token = {}
for i in range(98,123,2):
    token[chr(i)] = 0
l = [token.copy()]
for letter in string:
    if (ord(letter)+1)%2:
            token[letter] += 1
    l.append(token.copy())
q = int(input())
for query in range(q):
    a,b = map(int,input().split())
    if a > b:
        a,b = b,a
    ans = 0
    if a > len(string):
        a = len(string)
    if b > len(string):
        b = len(string)
    if a < 1:
        a = 1
    if b < 1:
        b = 1
    for i in range(98,123,2):
        if l[b][chr(i)] > l[a-1][chr(i)]:
            ans += 1
    print(ans)


Solve in Python:
There are total N friends went to Chef's Pizza shop. There they bought a pizza. Chef divided the pizza into K equal slices. Now you have to check whether these K pizza slices can be distributed equally among the friends. Also given that every person should get at least one slice. If the above conditions are possible then print "YES" otherwise print "NO".

-----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 integers N.
The second line of each test case contains K.

-----Output:-----
For each test case, print a single line containing "YES" if the given conditions are true else "NO" if the given conditions are false.

-----Constraints-----
1<=T<=10
1<=N<=10^6
1<=K<=10^6

-----Sample Input:-----
2
10
20
12
5

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

-----EXPLANATION:-----
Explanation case 1: since there are 10 friends and 20 pizza slice, so each can get 2 slices, so "YES".
Explanation case 2: Since there are 12 friends and only 5 pizza slice, so there is no way pizza slices can be distributed equally and each friend gets at least one pizza slice, so "NO".

for i in range(int(input())):
    x = int(input())
    y = int(input())
    if(y%x==0):
        print("YES")
    else:
        print("NO")# cook your dish here


Solve in Python:
There are two friends Alice and Bob. They have a packet of $n$ candies. They want to split the candies between them, and to do so, they kept them all in a single line. The $i^{\text{th}}$ candy in the line has a sweetness value of $a_i$. They decided to take turns in picking the candies. Alice has the first turn. In a person's turn, they either eat the leftmost candy or the rightmost candy with equal probability.
Can you find the expected value of sum of sweetness of the candies eaten by Alice?
Your answer is considered correct if its absolute or relative error doesn't exceed $10^{-6}$ .

-----Input:-----
- The first line will contain $T$, number of testcases. Then the testcases follow.
- First line of each testcase contains a single integer $n$ denoting the number of candies.
- Second line of each testcase contains  $n$ space separated integers representing $a_1,a_2,a_3,...a_n$ respectively.

-----Output:-----
For each testcase, output the expected value of sum of sweetness of the candies which Alice eats.

-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq n \leq 10^3$
- $1 \leq a_i \leq 10^6$
- Sum of $n$ across all the tests $\leq 10^3$

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

-----Sample Output:-----
1.500000000000000
4.000000000000000

-----EXPLANATION:-----
In the first sample, Alice eats either the first or the second candy with equal probability. Hence, expected value is $(1+2)/2 = 1.5$
For the second sample, expected value is $4$.

from sys import setrecursionlimit
setrecursionlimit(10 ** 9)

def solve(i, j, c=0):
 if i > j:
  return 0, 1

 if (i, j) in dp:
  return dp[i, j]

 if c == 0:
  x0, y0 = solve(i + 1, j, c ^ 1)
  x1, y1 = solve(i, j - 1, c ^ 1)

  dp[i, j] = x0 + x1 + a[i] * y0 + a[j] * y1, y0 + y1
  return x0 + x1 + a[i] * y0 + a[j] * y1, y0 + y1
 else:
  x0, y0 = solve(i + 1, j, c ^ 1)
  x1, y1 = solve(i, j - 1, c ^ 1)

  dp[i, j] = x0 + x1, y0 + y1
  return x0 + x1, y0 + y1

for _ in range(int(input())):
 n = int(input())
 a = list(map(int, input().split()))
 dp = {}

 total, total_count = solve(0, n-1)
 print(total / total_count)


Solve in Python:
There are two lists of different length. The first one consists of keys, the second one consists of values. Write a function ```createDict(keys, values)``` that returns a dictionary created from keys and values. If there are not enough values, the rest of keys should have a ```None``` value. If there not enough keys, just ignore the rest of values.

Example 1:
```python
keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3]
createDict(keys, values) # returns {'a': 1, 'b': 2, 'c': 3, 'd': None}
```

Example 2:
```python
keys = ['a', 'b', 'c']
values = [1, 2, 3, 4]
createDict(keys, values) # returns {'a': 1, 'b': 2, 'c': 3}
```

def createDict(keys, values):
    while len(keys) > len(values):
        values.append(None)

    dictionary = dict(list(zip(keys, values)))
    return dictionary


Solve in Python:
There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

class Solution:
     def findMedianSortedArrays(self, nums1, nums2):
         """
         :type nums1: List[int]
         :type nums2: List[int]
         :rtype: float
         """
         nums = sorted(nums1 + nums2)
         n = len(nums)
         return nums[int(n/2)] if n%2==1 else (nums[int(n/2)]+nums[int(n/2)-1])/2.0


Solve in Python:
There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:

Serve 100 ml of soup A and 0 ml of soup B
Serve 75 ml of soup A and 25 ml of soup B
Serve 50 ml of soup A and 50 ml of soup B
Serve 25 ml of soup A and 75 ml of soup B

When we serve some soup, we give it to someone and we no longer have it.  Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can.  We stop once we no longer have some quantity of both types of soup.
Note that we do not have the operation where all 100 ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.

Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.

Notes:

0 <= N <= 10^9.
Answers within 10^-6 of the true value will be accepted as correct.


Solve in Python:
There are N dominoes in a line, and we place each domino vertically upright.
In the beginning, we simultaneously push some of the dominoes either to the left or to the right.

After each second, each domino that is falling to the left pushes the adjacent domino on the left.
Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.
Return a string representing the final state.
Example 1:
Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."

Example 2:
Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.

Note:

0 <= N <= 10^5
String dominoes contains only 'L', 'R' and '.'

class Solution:
    def pushDominoes(self, dominoes: str) -> str:
        n = len(dominoes)
        force = [0] * n
        f = 0
        for i in range(n):
            if dominoes[i] == 'R':
                f = n
            elif dominoes[i] == 'L':
                f = 0
            else:
                f = max(f-1, 0)
            force[i] += f
        for i in range(n-1, -1, -1):
            if dominoes[i] == 'L':
                f = n
            elif dominoes[i] == 'R':
                f = 0
            else:
                f = max(f-1, 0)
            force[i] -= f
        return ''.join('.' if f==0 else 'R' if f > 0 else 'L' for f in force)


Solve in Python:
There are n people and 40 types of hats labeled from 1 to 40.
Given a list of list of integers hats, where hats[i] is a list of all hats preferred by the i-th person.
Return the number of ways that the n people wear different hats to each other.
Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:
Input: hats = [[3,4],[4,5],[5]]
Output: 1
Explanation: There is only one way to choose hats given the conditions.
First person choose hat 3, Second person choose hat 4 and last one hat 5.
Example 2:
Input: hats = [[3,5,1],[3,5]]
Output: 4
Explanation: There are 4 ways to choose hats
(3,5), (5,3), (1,3) and (1,5)

Example 3:
Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
Output: 24
Explanation: Each person can choose hats labeled from 1 to 4.
Number of Permutations of (1,2,3,4) = 24.

Example 4:
Input: hats = [[1,2,3],[2,3,5,6],[1,3,7,9],[1,8,9],[2,5,7]]
Output: 111

Constraints:

n == hats.length
1 <= n <= 10
1 <= hats[i].length <= 40
1 <= hats[i][j] <= 40
hats[i] contains a list of unique integers.

class Solution:
    def numberWays(self, hats: List[List[int]]) -> int:
        tot=len(hats)
        h=[[False]*tot for i in range(41)]
        for i in range(len(hats)):
            for j in range(len(hats[i])):
                h[hats[i][j]][i]=True

        f=[[0]*(1<<tot) for i in range(41)]
        f[0][0] = 1
        mod=10**9+7
        for i in range(41):
            for j in range(1<<tot):
                f[i][j] = (f[i][j] + f[i - 1][j])%mod
                for k in range(tot):
                    if (j & (1 << k))!=0 and h[i][k]:
                        f[i][j] = (f[i][j] + f[i - 1][j ^ (1 << k)]) % mod
        return f[40][(1 << tot) - 1]


Solve in Python:
There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:

Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
A team is valid if:  (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).

Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).

Example 1:
Input: rating = [2,5,3,4,1]
Output: 3
Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).

Example 2:
Input: rating = [2,1,3]
Output: 0
Explanation: We can't form any team given the conditions.

Example 3:
Input: rating = [1,2,3,4]
Output: 4

Constraints:

n == rating.length
1 <= n <= 200
1 <= rating[i] <= 10^5

class Solution:
    def numTeams(self, rating):
        self.count = 0
        def dfs(soldier, idx):
            if len(soldier) == 3:
                if soldier[0] < soldier[1] < soldier[2] or soldier[0] > soldier[1] > soldier[2]:
                    self.count += 1
                return
                # 5 % 3
            for i in range(idx, len(rating)):
                soldier.append(rating[i])
                dfs(soldier, i + 1)
                soldier.pop()
        dfs([],0)
        return self.count


Solve in Python:
There exist certain strings, known as $Unique$ $Strings$. They possess a unique property:
- The character 'c' gets converted to "ff" and the character 'k' gets converted to "gg". Any letter besides 'c' and 'k' does not get converted to any other character.
Your job is to count the number of strings that could possibly be represented by a given unique string. Since the value could be very large, output the remainder when divided by $10^9+7$.
Note that if the given string is not a unique string, i.e. it contains either 'c' or 'k', output $0$.

-----Input:-----
- The first line of input contains a string, $s$.

-----Output:-----
- Output in a single line the possible number of strings modulo $10^9+7$.

-----Constraints-----
- $1 \leq |s| \leq 10^5$
where |s| denotes length of string.

-----Sample Input 1:-----
thing

-----Sample Input 2:-----
ggdffn

-----Sample Input 3:-----
fff

-----Sample Input 4:-----
cat

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

-----Sample Output 2:-----
4

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

-----Sample Output 4:-----
0

-----EXPLANATION:-----
The possible strings that can be represented by the given string in each of the examples are as follows:
$1)$ 'thing'
$2)$ 'ggdffn','kdffn','ggdcn','kdcn'
$3)$ 'fff','cf','fc'
$4)$ Since the string 'cat' contains 'c', it is certain that this string is not a unique string. Hence, the output is $0$.

from itertools import combinations as cb

s = input()
s = list(s)
if('c' in s or 'k' in s):
 print('0')
else:
 nf = []
 nk =[]
 i =0
 while i<len(s)-1:
  if(s[i]=='f'):
   j=i+1
   p=1
   k =1
   while j<len(s) and p:
    if(s[j]=='f'):
     k+=1
     j +=1
    else:
     p=0
   nf.append(k)
   i = j
  elif(s[i]=='g'):
   j = i+1
   p=1
   k=1
   while j<len(s) and p:
    if(s[j]=='g'):
     k+=1
     j+=1
    else:
     p=0

   nk.append(k)
   i = j
  else:
   i+=1

 p=1
 for i in nf:
  n = i
  if(n>=2):
   k=0
   for j in range(1,n+1):
    a = (n//j) -1
    k +=a
   k+=1
   p *=k
 for i in nk:
  n = i
  if(n>=2):
   k=0
   for j in range(1,n+1):
    a = (n//j) -1
    k +=a
   k+=1
   p *=k
 if(nf!=[] and nk!=[]):
  if(len(s)==nf[0] or len(s)==nk[0]):
   count =p-1
  else:
   count =p
 elif(nf==[] and nk!=[]):
  if( len(s)==nk[0]):
   count =p-1
  else:
   count =p
 elif(nf!=[] and nk==[]):
  if(len(s)==nf[0]):
   count =p-1
  else:
   count =p
 else:
  count =1
 print(count%1000000007)


Solve in Python:
There exist two zeroes: +0 (or just 0) and -0.

Write a function that returns `true` if the input number is -0 and `false` otherwise (`True` and `False` for Python).

In JavaScript / TypeScript / Coffeescript the input will be a number.

In Python / Java / C / NASM / Haskell / the input will be a float.

import math
def is_negative_zero(n):
    return n == 0 and math.copysign(1, n) == -1


Solve in Python:
There is Chef and Chef’s Crush who are playing a game of numbers.

Chef’s crush has a number $A$ and Chef has a number $B$.

Now, Chef wants Chef’s crush to win the game always, since she is his crush. The game ends when the greatest value of A^B is reached after performing some number of operations (possibly zero), Where ^ is Bitwise XOR.

Before performing any operation you have to ensure that both $A$ and $B$ have the same number of bits without any change in the values. It is not guaranteed that $A$ and $B$ should have same number of bits in the input.
For example, if $A$ is $2$ and $B$ is $15$, then the binary representation of both the numbers will have to be $0010$ and $1111$ respectively, before performing any operation.
The operation is defined as  :
- Right circular shift of the bits of only $B$ from MSB$_B$ to LSB$_B$ i.e. if we consider $B_1 B_2 B_3 B_4$ as binary number, then after one circular right shift, it would be $B_4 B_1 B_2 B_3$
They both are busy with themselves, can you find the number of operations to end the game?

-----Input :-----
- The first line of input contains $T$, (number of test cases)
- Then each of the next $T$ lines contain : two integers $A$ and $B$ respectively.

-----Output :-----
For each test case print two space-separated integers, The number of operations to end the game and value of A^B when the game ends.

-----Constraints :-----
- $1 \leq T \leq100$
- $1\leq A,B \leq 10^{18}$

-----Subtasks  :-----
- 30 Points: $1\leq A,B \leq 10^5$
- 70 Points: Original Constraints

-----Sample Input :-----
1
4 5

-----Sample Output :-----
2 7

-----Explanation  :-----
Binary  representation of  $4$ is $100$ and binary  representation  $5$ is $101$.
- After operation $1$ : $B$ $=$ $110$, so A^B $=$ $2$
- After operation $2$ : $B$ $=$ $011$, so A^B $=$ $7$
So, the value of A^B will be $7$. Which is the greatest possible value for A^B and the number of operations are $2$.

try:
 def ts(s):
  str1 = ""
  for ele in s:
   str1 += ele
  return str1

 for _ in range(int(input())):
  x,y=[int(x) for x in input().split()]
  x=list(bin(x).replace("0b", ""))
  y=list(bin(y).replace("0b",""))
  xl=len(x)
  yl=len(y)
  if(xl<yl):
   for __ in range(yl-xl):
    x.insert(0,'0')
  else:
   for __ in range(xl-yl):
    y.insert(0,'0')
  l=len(x)
  xor=-1
  rotations=-1
  for i in range(l):
   temp_xor=int(ts(x),2)^int(ts(y),2)
   if(temp_xor>xor):
    xor=temp_xor
    rotations=i
   temp=x.pop
   y.insert(0,y.pop())
  print(rotations,xor)

except:
 pass


Solve in Python:
There is a big staircase with $N$ steps (numbered $1$ through $N$) in ChefLand. Let's denote the height of the top of step $i$ by $h_i$. Chef Ada is currently under the staircase at height $0$ and she wants to reach the top of the staircase (the top of the last step). However, she can only jump from height $h_i$ to the top of a step at height $h_f$ if $h_f-h_i \le K$. To help Ada, we are going to construct some intermediate steps; each of them may be constructed between any two steps, or before the first step, and have any height. What is the minimum number of steps that need to be added to the staircase so that Ada could reach the top?

-----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 $K$.
- The second line contains $N$ space-seperated integers $h_1, h_2, \dots, h_N$.

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

-----Constraints-----
- $1 \le T \le 64$
- $1 \le N \le 128$
- $1 \le K \le 1,024$
- $1 \le h_i \le 1,024$ for each valid $i$
- $h_i < h_{i+1}$ for each valid $i$

-----Example Input-----
1
4 3
2 4 8 16

-----Example Output-----
3

# cook your dish here
for _ in range(int(input())):
 N, K = list(map(int, input().split()))
 h = list(map(int, input().split()))
 h.insert(0,0)
 c = 0
 for i in range(1, N+1):
  c += (h[i] - h[i-1] - 1) // K
 print(c)


Solve in Python:
There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.

The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.

If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.

You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

Example:

Input:
[[1,2,2,1],
 [3,1,2],
 [1,3,2],
 [2,4],
 [3,1,2],
 [1,3,1,1]]
Output: 2
Explanation:

Note:

The width sum of bricks in different rows are the same and won't exceed INT_MAX.
The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000.

class Solution:
     def leastBricks(self, wall):
         """
         :type wall: List[List[int]]
         :rtype: int
         """
         if not wall:
             return 0

         width = sum(wall[0])
         length = len(wall)
         columns = collections.defaultdict(lambda: length)

         for r in range(len(wall)):
             col = 0
             for c in range(len(wall[r])-1):
                 col += wall[r][c]
                 columns[col] -= 1

         return length if len(columns) == 0 else min(columns.values())


Solve in Python:
There is a building with $N$ floors (numbered $1$ through $N$ from bottom to top); on each floor, there are $M$ windows (numbered $1$ through $M$ from left to right). Let's denote the $j$-th window on the $i$-th floor by $(i, j)$.
All windows in the building need to be cleaned one by one in a specific order. You are given this order as a matrix $A$ with $N$ rows and $M$ columns; for each valid $i$ and $j$, the window $(i, j)$ must be cleaned on the $A_{N-i+1,j}$-th turn.
Whenever we clean a window $(i, j)$, it becomes clean, but the dirty water used for cleaning it flows down to windows $(i-1, j-1)$, $(i-1, j)$ and $(i-1, j+1)$ (more precisely, to all of these windows which exist), so these windows become dirty again. Then, the water flows further down, so the same applies for other windows below: whenever a window $(i, j)$ becomes dirty, windows $(i-1, j-1)$, $(i-1, j)$ and $(i-1, j+1)$ become dirty as well. For example, cleaning a window $(5, 3)$ will make the window $(3, 2)$ dirty. The next window is cleaned only after water flows down completely. Note that each window is cleaned only once and there may be dirty windows at the end.
For each window, determine whether it will be clean after the cleaning process ends.

-----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 $M$.
- $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains $M$ space-separated integers $A_{i, 1}, A_{i, 2}, \ldots, A_{i, M}$.

-----Output-----
For each test case, print $N$ lines; each of them should contain a string with length $M$. For each valid $i$ and $j$, the $j$-th character on the $i$-th line should be '1' if the window $(N-i+1, j)$ is clean or '0' if it is dirty.

-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N, M \le 10^3$
- $1 \le A_{i, j} \le N \cdot M$ for each valid $i, j$
- the elements of the matrix $A$...

R = lambda : map(int, input().split())
f = lambda x: ([0] + x, x, x[1:] + [0])

t, = R()
for _ in range(t):
  n, m = R()
  a = b = [0] * m
  for _ in range(n):
    a = list(map(max, *f(a), *f(b)))
    b = list(R())
    print(''.join('01'[x < y] for x, y in zip(a, b)))


Solve in Python:
There is a city with $N$ numbered $0 - N-1$ shops. A market is a place where we can reach from one shop to another using some road. There are $M$ roads in this city connecting each connecting any two shops.
Find the number of markets in the city.
NOTE:  A market having only one shop is also a valid market.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- First line of Each Test Case is $N, M$, denoting the number of shops and the number of roads respectively.
- Next M lines consist of two integers $A$ and $B$ denoting that there exists a road between Shop A and Shop B

-----Output:-----
For each testcase, output the number of markets.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N,M \leq 10^3$
- $0 \leq A,B < N$

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

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

class DSU(object):
    def __init__(self, n):
        self.parents = [i for i in range(n)]

    def find(self,x):
        if self.parents[x] != x:
            self.parents[x] = self.find(self.parents[x])
        return self.parents[x]

    def union(self, x, y):
        rootA, rootB = self.find(x), self.find(y)
        if rootA != rootB:
            self.parents[rootA] = rootB

def solve():
	n,m=map(int,input().split())
	dsu=DSU(n)
	for i in range(m):
		x,y=map(int,input().split())
		dsu.union(x,y)
	cnt=0
	for i,x in enumerate(dsu.parents):
		cnt+=(i==x)
	print(cnt)

t=int(input())
while t:
	solve()
	t-=1


Solve in Python:
There is a country with $n$ citizens. The $i$-th of them initially has $a_{i}$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.

Sometimes the government makes payouts to the poor: all citizens who have strictly less money than $x$ are paid accordingly so that after the payout they have exactly $x$ money. In this case the citizens don't send a receipt.

You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.

-----Input-----

The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{5}$) — the numer of citizens.

The next line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_{i} \le 10^{9}$) — the initial balances of citizens.

The next line contains a single integer $q$ ($1 \le q \le 2 \cdot 10^{5}$) — the number of events.

Each of the next $q$ lines contains a single event. The events are given in chronological order.

Each event is described as either 1 p x ($1 \le p \le n$, $0 \le x \le 10^{9}$), or 2 x ($0 \le x \le 10^{9}$). In the first case we have a receipt that the balance of the $p$-th person becomes equal to $x$. In the second case we have a payoff with parameter $x$.

-----Output-----

Print $n$ integers — the balances of all citizens after all events.

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

Output
3 2 3 4

Input
5
3 50 2 1 10
3
1 2 0
2 8
1 3 20

Output
8 8 20 8 10

-----Note-----

In the first example the balances change as follows: 1 2 3 4 $\rightarrow$ 3 3 3 4 $\rightarrow$ 3 2 3 4 $\rightarrow$ 3 2 3 4

In the second example the balances change as follows: 3 50 2 1 10 $\rightarrow$ 3 0 2 1 10 $\rightarrow$ 8 8 8 8 10 $\rightarrow$ 8 8 20 8 10

n=int(input())
a=list(map(int,input().split()))
q=int(input())
changes=[0]*q
for i in range(q):
    changes[-i-1]=tuple(map(int,input().split()))
final=[-1]*n
curr=0
for guy in changes:
    if guy[0]==1:
        if final[guy[1]-1]==-1:
            final[guy[1]-1]=max(guy[2],curr)
    else:
        curr=max(curr,guy[1])
for i in range(n):
    if final[i]==-1:
        final[i]=max(curr,a[i])
final=[str(guy) for guy in final]
print(" ".join(final))


Solve in Python:
There is a directed graph with N vertices and N edges. The vertices are numbered 1, 2, ..., N.
The graph has the following N edges: (p_1, 1), (p_2, 2), ..., (p_N, N), and the graph is weakly connected. Here, an edge from Vertex u to Vertex v is denoted by (u, v), and a weakly connected graph is a graph which would be connected if each edge was bidirectional.
We would like to assign a value to each of the vertices in this graph so that the following conditions are satisfied. Here, a_i is the value assigned to Vertex i.
 - Each a_i is a non-negative integer.
 - For each edge (i, j), a_i \neq a_j holds.
 - For each i and each integer x(0 ≤ x < a_i), there exists a vertex j such that the edge (i, j) exists and x = a_j holds.
Determine whether there exists such an assignment.

-----Constraints-----
 - 2 ≤ N ≤ 200 000
 - 1 ≤ p_i ≤ N
 - p_i \neq i
 - The graph is weakly connected.

-----Input-----
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N

-----Output-----
If the assignment is possible, print POSSIBLE; otherwise, print IMPOSSIBLE.

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

-----Sample Output-----
POSSIBLE

The assignment is possible: {a_i} = {0, 1, 0, 1} or {a_i} = {1, 0, 1, 0}.

import sys
sys.setrecursionlimit(10**6)
n = int(input())
p = list(map(int, input().split()))
c = [[] for _ in range(n)]
is_leaf = [True for _ in range(n)]
for i in range(n):
	p[i] -= 1
	c[p[i]].append(i)
	is_leaf[p[i]] = False

if sum(is_leaf) == 0:
	if n%2 == 0:
		print("POSSIBLE")
	else:
		print("IMPOSSIBLE")
	return

for i in range(n):
	if is_leaf[i]:
		cur = i
		break

visited_set = {cur}
visited_list = [cur]
while p[cur] not in visited_set:
	visited_list.append(p[cur])
	visited_set.add(p[cur])
	cur = p[cur]

root = p[cur]

grundy = [-1 for _ in range(n)]
g_set = [set() for _ in range(n)]

def dfs(x):
	res = 0
	for v in c[x]:
		dfs(v)
		g_set[x].add(grundy[v])
	while res in g_set[x]:
		res += 1
	grundy[x] = res
	return res

loop = [False for _ in range(n)]
loop[root] = True
ind = len(visited_list)-1
while visited_list[ind] != root:
	loop[visited_list[ind]] = True
	ind -= 1
#print(loop)

for i in range(n):
	if loop[i]:
		for x in c[i]:
			if not loop[x]:
				dfs(x)
				g_set[i].add(grundy[x])

cand = []
num = 0
while num in g_set[root]:
	num += 1
cand.append(num)
num += 1
while num in g_set[root]:
	num += 1
cand.append(num)

for x in cand:
	cur = root
	grundy[root] = x
	while True:
		num = 0
		while num in g_set[p[cur]] or num == grundy[cur]:
			num += 1
		grundy[p[cur]] = num
		if p[cur] == root:
			break
		cur = p[cur]
	if grundy[root] == x:
		#print(grundy)
		print("POSSIBLE")
		return

print("IMPOSSIBLE")


Solve in Python:
There is a field with plants — a grid with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$); out of its $NM$ cells, $K$ cells contain plants, while the rest contain weeds. Two cells are adjacent if they have a common side.
You want to build fences in the field in such a way that the following conditions hold for each cell that contains a plant:
- it is possible to move from this cell to each adjacent cell containing a plant without crossing any fences
- it is impossible to move from this cell to any cell containing weeds or to leave the grid without crossing any fences
The fences can only be built between cells or on the boundary of the grid, i.e. on the sides of cells. The total length of the built fences is the number of pairs of side-adjacent cells such that there is a fence built on their common side plus the number of sides of cells on the boundary of the grid which have fences built on them. Find the minimum required total length of fences that need to be built.

-----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 three space-separated integers $N$, $M$ and $K$.
- $K$ lines follow. Each of these lines contains two space-separated integers $r$ and $c$ denoting that the cell in row $r$ and column $c$ contains a plant.

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

-----Constraints-----
- $1 \le T \le 10$
- $1 \le N, M \le 10^9$
- $1 \le K \le 10^5$
- $1 \le r \le N$
- $1 \le c \le M$
- the cells containing plants are pairwise distinct

-----Subtasks-----
Subtask #1 (30 points): $1 \le N, M \le 1,000$
Subtask #2 (70 points): original constraints

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

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

-----Explanation-----
Example case 1: The field looks like this ('x' denotes a cell containing a plant,...

# https://www.codechef.com/APRIL19B/problems/FENCE
'''
    Author - Subhajit Das
    University of Engineering and Management, Kolkata
    04/07/2019
'''

def main():
 for _ in range(int(input())):
  n, m, k = list(map(int, input().split()))
  plants = dict()
  ans = 0
  while(k != 0):
   r, c = list(map(int, input().split()))
   plants[(r,c)] = True
   ans += 4
   if(plants.get((r+1,c),False)):
    ans -= 2
   if(plants.get((r-1,c),False)):
    ans -= 2
   if(plants.get((r,c+1),False)):
    ans -= 2
   if(plants.get((r,c-1),False)):
    ans -= 2
   k -= 1
  print(ans)

def __starting_point():
 main()

__starting_point()


Solve in Python:
There is a frog staying to the left of the string $s = s_1 s_2 \ldots s_n$ consisting of $n$ characters (to be more precise, the frog initially stays at the cell $0$). Each character of $s$ is either 'L' or 'R'. It means that if the frog is staying at the $i$-th cell and the $i$-th character is 'L', the frog can jump only to the left. If the frog is staying at the $i$-th cell and the $i$-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell $0$.

Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.

The frog wants to reach the $n+1$-th cell. The frog chooses some positive integer value $d$ before the first jump (and cannot change it later) and jumps by no more than $d$ cells at once. I.e. if the $i$-th character is 'L' then the frog can jump to any cell in a range $[max(0, i - d); i - 1]$, and if the $i$-th character is 'R' then the frog can jump to any cell in a range $[i + 1; min(n + 1; i + d)]$.

The frog doesn't want to jump far, so your task is to find the minimum possible value of $d$ such that the frog can reach the cell $n+1$ from the cell $0$ if it can jump by no more than $d$ cells at once. It is guaranteed that it is always possible to reach $n+1$ from $0$.

You have to answer $t$ independent test cases.

-----Input-----

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

The next $t$ lines describe test cases. The $i$-th test case is described as a string $s$ consisting of at least $1$ and at most $2 \cdot 10^5$ characters 'L' and 'R'.

It is guaranteed that the sum of lengths of strings over all test cases does not exceed $2 \cdot 10^5$ ($\sum |s| \le 2 \cdot 10^5$).

-----Output-----

For each test case, print the answer — the minimum possible value of $d$ such that the frog can reach the cell $n+1$ from the cell $0$ if it jumps by no more than $d$ at...

import sys
input=sys.stdin.readline
for j in range(int(input())):
    a = input()
    a = a + 'R'
    ans = 1
    count =0
    for j in a:
        if(j=='L'):
            count= count + 1
        else:
            count = count + 1
            if(count>ans):
                ans = count
            count = 0
    print(ans)


Solve in Python:
There is a girl named ''Akansha''. She is very fond of eating chocolates but she has a weak immune system due to which she gets cold after eating chocolate during morning, evening and night and can only eat at most $x$ number of chocolate each afternoon. A friend of hers gifted her some $n$ number of chocolates that she doesn't want to share with anyone. Those chocolate have to be finished before they expire. (no. of days in which they are going to expire from the day she has been gifted the chocolate is given for each chocolate)   $Note:$ Chocolate cannot be consumed on the day it expires.

Help Akansha to know if it is possible for her to finish all the chocolates before they expire or not.

-----Input:-----
- First line will contain $T$, number of test cases. Then the test cases follow.
- First line contains $n$,the number of chocolates gifted to her
- Second line contains $x$,the number of chocolates she can eat each afternoon
- Third line contains $n$ space separated integers $A1,A2...An$,denoting the expiry of each of the $n$ chocolates

-----Output:-----
For each testcase, print $Possible$, if she can complete all the chocolates gifted to her. Otherwise, print $Impossible$, if she can not finish all the chocolates.

-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq n \leq 1500$
- $1 \leq x \leq 1500$
- $1 \leq Ai \leq 1500$

-----Subtasks-----
- 100 points : $Original Constraints$

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

3

5

4 1 2

5

2

4 4 3 2 2

5

1

4 2 3 1 1

-----Sample Output:-----
Impossible

Possible

Impossible

-----EXPLANATION:-----
-
Example case 1

1st and 3rd chocolate on the 1st afternoon as she can consume at most 5. one chocolate will be wasted.
$Note:$ she cannot eat the 2nd chocolate because chocolates cannot be consumed on the day of expiry.
-
Example case 2

4th and 5th chocolate on 1st afternoon, 3rd and 1st chocolate on 2nd afternoon. And 2nd chocolate on the 3rd afternoon.
It will take a total of 3 days to finish the chocolate.
-
Example case 3

She cannot eat 4th and 5th...

def woow(l,oned):
 if 1 in l:
  return False
 else:
  for i in range(2,len(l)-1):
   if (l.count(i)>oned):
    lm=l.count(i)//i
    for tp in range(1,lm):
     if i+tp in l:
      return False
  return True
tc=int(input())
for tcc in range(1,tc+1):
 chocs=int(input())
 oned=int(input())
 l=list(map(int,input().split()))
 if woow(l,oned)==True:
  print("Possible")
 else:
  print("Impossible")


Solve in Python:
There is a group of G members, and a list of various crimes they could commit.
The ith crime generates a profit[i] and requires group[i] members to participate in it.
If a member participates in one crime, that member can't participate in another crime.
Let's call a profitable scheme any subset of these crimes that generates at least P profit, and the total number of members participating in that subset of crimes is at most G.
How many schemes can be chosen?  Since the answer may be very large, return it modulo 10^9 + 7.

Example 1:
Input: G = 5, P = 3, group = [2,2], profit = [2,3]
Output: 2
Explanation:
To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.

Example 2:
Input: G = 10, P = 5, group = [2,3,5], profit = [6,7,8]
Output: 7
Explanation:
To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).

Note:

1 <= G <= 100
0 <= P <= 100
1 <= group[i] <= 100
0 <= profit[i] <= 100
1 <= group.length = profit.length <= 100

class Solution:
    def profitableSchemes(self, G: int, P: int, group: List[int], profit: List[int]) -> int:
        memo =[[0]*(G+1) for _ in range(P+1)]
        memo[0][0]=1
        for p,g in zip(profit,group):
            for i in range(P,-1,-1):
                for j in range(G-g,-1,-1):
                    memo[min(P,p+i)][j+g] += memo[i][j]
        return sum(memo[P])%(10**9+7)


Solve in Python:
There is a haunted town called HauntedLand. The structure of HauntedLand can be thought of as a grid of size n * m. There is a house in each cell of the grid. Some people have fled from their houses because they were haunted. '.' represents a haunted house whereas '*' represents a house in which people are living.

One day, Devu, the famous perfumer came to town with a perfume whose smell can hypnotize people. Devu can put the perfume in at most one of the houses. This takes Devu one second. Then, the perfume spreads from one house (need not be inhabited by people) to all its adjacent houses in one second, and the cycle continues. Two houses are said to be a adjacent to each other, if they share a corner or an edge, i.e., each house (except those on the boundaries) will have 8 adjacent houses.

You want to save people from Devu's dark perfumery by sending them a message to flee from the town. So, you need to estimate the minimum amount of time Devu needs to hypnotize all the people? Note that if there are no houses inhabited by people, Devu doesn't need to put perfume in any cell.

-----Input-----
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
First line of each test case contains two space separated integers n, m denoting the dimensions of the town.
For each of next n lines, each line has m characters (without any space) denoting a row of houses of the town.

-----Output-----
For each test case, output a single integer corresponding to the answer of the problem.

-----Constraints-----
- 1 ≤ T ≤ 20
Subtask #1: (40 points)

- 1 ≤ n, m ≤ 100Subtask #2: (60 points)

- 1 ≤ n, m ≤ 1000

-----Example-----
Input:
2
2 2
*...
3 4
.*..***..*..

Output:
1
2

-----Explanation-----
In the first example, it will take Devu one second for putting the perfume at the only house. So, the answer is 1.

In the second example, He will first put the perfume at the * at cell (1, 1) (assuming 0-based indexing).

Now, it will take Devu 1 secs to put perfume....

import math
t=eval(input())
while t>0:
 n,m=list(map(int,input().split()))
 f=[]
 min_x,max_x,min_y,max_y=1001,-1,1001,-1
 for x in range(n):
  f.append(input().strip())
 for i in range(n):
  for j in range(m):
   if f[i][j]=='*':
    if min_x>i:
     min_x=i
    if max_x<i:
     max_x=i
    if min_y>j:
     min_y=j
    if max_y<j:
     max_y=j
    #print 'min_x=',min_x,'min_y=',min_y,'max_x=',max_x,'max_y='                    ,max_y
 if max_x==-1 or min_x==1001 or max_y==-1 or max_y==1001:
  print(0)
 else:
  dx=max_x-min_x
  dy=max_y-min_y
  res=0
  if dx>dy:
   res=int(math.ceil(dx/2.0))+1
  else:
   res=int(math.ceil(dy/2.0))+1
  if res>0:
   print(res)
  else:
   print(res)
 t-=1


Solve in Python:
There is a house with 4 levels.
In that house there is an elevator.
You can program this elevator to go up or down,
depending on what button the user touches inside the elevator.

Valid levels must be only these numbers: `0,1,2,3`

Valid buttons must be only these strings: `'0','1','2','3'`

Possible return values are these numbers: `-3,-2,-1,0,1,2,3`

If the elevator is on the ground floor(0th level)
and the user touches button '2'
the elevator must go 2 levels up,
so our function must return 2.

If the elevator is on the 3rd level
and the user touches button '0'
the elevator must go 3 levels down, so our function must return -3.

If the elevator is on the 2nd level,
and the user touches button '2'
the elevator must remain on the same level,
so we return 0.

We cannot endanger the lives of our passengers,
so if we get erronous inputs,
our elevator must remain on the same level.
So for example:

- `goto(2,'4')` must return 0, because there is no button '4' in the elevator.
- `goto(4,'0')` must return 0, because there is no level 4.
- `goto(3,undefined)` must return 0.
- `goto(undefined,'2')` must return 0.
- `goto([],'2')` must return 0 because the type of the input level is array instead of a number.
- `goto(3,{})` must return 0 because the type of the input button is object instead of a string.

def goto(l,b):
    if b in ('0','1','2','3') and l in (0,1,2,3):
        return int(b)-l
    return 0


Solve in Python:
There is a new prodigy in town and he has challenged people to a game. They have to give him an integer N and he will immediately respond with a number which has more than N factors.
What the prodigy really does is to do some complex calculations in his head to find out the smallest integer with more than N factors. However, he has a weakness - he knows to do those calculation only on numbers up to 1019, so if the answer to be reported is more than 1019, he will not be able to come up with his solution and will lose the game.
Given the integer the people give to the prodigy, you need to report whether he wins the game or not. If he wins, also output his answer.

-----Input-----
The first line of input contains T (T ≤ 25), the number of test cases. Following this are T lines, each containing an integer N (1 ≤ N ≤ 109) - the number which is given to the prodigy.

-----Output-----
Output one line per test case. If the smallest integer X with more than N factors is bigger than 1019 so that the prodigy does not win, print "lose". Otherwise print "win X" (quotes for clarity).

-----Example-----
Input:
3
3
5
12345678

Output:
win 6
win 12
lose


Solve in Python:
There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).
There are n + 1 taps located at points [0, 1, ..., n] in the garden.
Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.
Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.

Example 1:

Input: n = 5, ranges = [3,4,1,1,0,0]
Output: 1
Explanation: The tap at point 0 can cover the interval [-3,3]
The tap at point 1 can cover the interval [-3,5]
The tap at point 2 can cover the interval [1,3]
The tap at point 3 can cover the interval [2,4]
The tap at point 4 can cover the interval [4,4]
The tap at point 5 can cover the interval [5,5]
Opening Only the second tap will water the whole garden [0,5]

Example 2:
Input: n = 3, ranges = [0,0,0,0]
Output: -1
Explanation: Even if you activate all the four taps you cannot water the whole garden.

Example 3:
Input: n = 7, ranges = [1,2,1,0,2,1,0,1]
Output: 3

Example 4:
Input: n = 8, ranges = [4,0,0,0,0,0,0,0,4]
Output: 2

Example 5:
Input: n = 8, ranges = [4,0,0,0,4,0,0,0,4]
Output: 1

Constraints:

1 <= n <= 10^4
ranges.length == n + 1
0 <= ranges[i] <= 100

class Solution:
    def minTaps(self, n: int, ranges: List[int]) -> int:
        min_range, max_range, open_taps = 0, 0 ,0

        while max_range < n:
            for i, r in enumerate(ranges):
                if i - r <= min_range and i + r >= max_range:
                    max_range = i + r

            if min_range == max_range:
                return -1
            open_taps += 1
            min_range = max_range

        return open_taps


Solve in Python:
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:

You will pick any pizza slice.
Your friend Alice will pick next slice in anti clockwise direction of your pick.
Your friend Bob will pick next slice in clockwise direction of your pick.
Repeat until there are no more slices of pizzas.

Sizes of Pizza slices is represented by circular array slices in clockwise direction.
Return the maximum possible sum of slice sizes which you can have.

Example 1:

Input: slices = [1,2,3,4,5,6]
Output: 10
Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.

Example 2:

Input: slices = [8,9,8,6,1,1]
Output: 16
Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.

Example 3:
Input: slices = [4,1,2,5,8,3,1,9,7]
Output: 21

Example 4:
Input: slices = [3,1,2]
Output: 3

Constraints:

1 <= slices.length <= 500
slices.length % 3 == 0
1 <= slices[i] <= 1000

class Solution:
    def maxSizeSlices(self, slices: List[int]) -> int:
        n=len(slices)
        dp=[[0 for j in range(n//3)] for i in range(n)]

        dp[0][0]=slices[0]

        for i in range(1,n):
            dp[i][0]=max(dp[i-1][0],slices[i])

        for i in range(2,n):
            for j in range(1,min(i//2+1,n//3)):
                dp[i][j]=max(dp[i-1][j],dp[i-2][j-1]+slices[i])

        mx=0

        for i in range(n-1):
            mx=max(mx,dp[i][-1])

        for i in range(n):
            for j in range(n//3):
                dp[i][j]=0

        for i in range(1,n):
            dp[i][0]=max(dp[i-1][0],slices[i])

        for i in range(2,n):
            for j in range(1,min(i//2+1,n//3)):
                dp[i][j]=max(dp[i-1][j],dp[i-2][j-1]+slices[i])

        mx=max(mx,dp[-1][-1])
        return mx