Solve in Python:
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.

If there are multiple solutions, return any subset is fine.

Example 1:

nums: [1,2,3]

Result: [1,2] (of course, [1,3] will also be ok)

Example 2:

nums: [1,2,4,8]

Result: [1,2,4,8]

Credits:Special thanks to @Stomach_ache for adding this problem and creating all test cases.

from math import sqrt
 class Solution:
     def largestDivisibleSubset(self, nums):
         """
         :type nums: List[int]
         :rtype: List[int]
         """
         nums.sort()
         l, prev = {}, {}  # length, previous number(largest divisor in nums)
         max_l, end_number = 0, None

         for i in nums:
             tmp_l, tmp_prev = 0, None
             for j in range(1, 1 + int(sqrt(i))):
                 if i % j == 0:
                     tmp = i // j
                     if tmp in prev and l[tmp] > tmp_l:
                         tmp_l, tmp_prev = l[tmp], tmp
                     if j in prev and l[j] > tmp_l:
                         tmp_l, tmp_prev = l[j], j

             tmp_l += 1
             prev[i], l[i] = tmp_prev, tmp_l

             if tmp_l > max_l:
                 max_l, end_number = tmp_l, i

         ans = []
         while end_number is not None:
             ans.append(end_number)
             end_number = prev[end_number]

         return ans


Solve in Python:
Given a set of elements (integers or string characters) that may occur more than once, we need to know the amount of subsets that none of their values have repetitions.
Let's see with an example:
```
set numbers = {1, 2, 3, 4}
```
The subsets are:
```
{{1}, {2}, {3}, {4}, {1,2}, {1,3}, {1,4}, {2,3}, {2,4},{3,4}, {1,2,3}, {1,2,4}, {1,3,4}, {2,3,4}, {1,2,3,4}} (15 subsets, as you can see the empty set, {}, is not counted)
```
Let's see an example with repetitions of an element:
```
set letters= {a, b, c, d, d}
```
The subsets for this case will be:
```
{{a}, {b}, {c}, {d}, {a,b}, {a,c}, {a,d}, {b,c}, {b,d},{c,d}, {a,b,c}, {a,b,d}, {a,c,d}, {b,c,d}, {a,b,c,d}} (15 subsets, only the ones that have no repeated elements inside)
```

The function ```est_subsets()``` (javascript: ``estSubsets()```) will calculate the number of these subsets.
It will receive the array as an argument and according to its features will output the amount of different subsets without repetitions of its elements.
```python
est_subsets([1, 2, 3, 4]) == 15
est_subsets(['a', 'b', 'c', 'd', 'd']) == 15
```
Features of the random tests:
```
Low Performance Tests: 40
Length of the arrays between 6 and 15

High Performance Tests: 80
Length of the arrays between 15 and 100 (Python an Ruby) and between 15 and 50 javascript)
```
Just do it!

def est_subsets(arr):
    return 2**len(set(arr)) - 1


Solve in Python:
Given a set of integers _S_, the _closure of S under multiplication_ is the smallest set that contains _S_ and such that for any _x, y_ in the closure of _S_, the product _x * y_ is also in the closure of _S_.

Example 1: Given `S = {2}`, the closure of `S` is the set `{2, 4, 8, 16, 32, 64, ... }`.

Example 2: Given `S = {1, 2, 3}`, the closure of `S` is the set `{1, 2, 3, 4, 6, 8, 9, 12, 16, 18, 24, 27, 32, 36, ...}`. This set contains, e.g, `6` because `6 = 2 * 3`. It further contains `12` and `18` because `12 = 2 * 6` and `18 = 3 * 6`. Etc.

Example 3: Given `S` the set of prime numbers, the closure of `S` is the set of all positive integers greater than or equal to `2`.

Your task is two write a generator function that generates the members of the closure of any given _finite_ set of positive numbers `S` in _ascending order_.

def closure_gen(*s):
    s = [*s]

    if 1 in s:
        s.remove(1)
        yield 1

    queue = [(n, n, 0) for n in s]
    numbers = [1]

    while queue:
        prod, *_ = min(queue)
        yield prod

        numbers.append(prod)
        for i, (p, n, d) in enumerate(queue):
            if p <= prod:
                d += p == prod
                queue[i] = numbers[d] * n, n, d


Solve in Python:
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.

~~~if-not:racket
```
invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []
```
~~~

```if:javascript,python,ruby,php,elixir,dart
You can assume that all values are integers. Do not mutate the input array/list.
```

```if:c
### Notes:
- All values are greater than `INT_MIN`
- The input should be modified, not returned.
```
~~~if:racket
```racket
(invert '(1 2 3 4 5))   ; '(-1 -2 -3 -4 -5)
(invert '(1 -2 3 -4 5)) ; '(-1 2 -3 4 -5)
(invert '())            ; '()
```
~~~

def invert(lst):
    for x, y in enumerate(lst):
        lst[x] *= -1
    return lst


Solve in Python:
Given a set of points in the xy-plane, determine the minimum area of a rectangle formed from these points, with sides parallel to the x and y axes.
If there isn't any rectangle, return 0.

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

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

Note:

1 <= points.length <= 500
0 <= points[i][0] <= 40000
0 <= points[i][1] <= 40000
All points are distinct.

class Solution:
    def minAreaRect(self, points: List[List[int]]) -> int:
      #  if points == [] or points == [[]] or points == None or len(points) < 4:
      #      return 0

        seen = set()
        res = float('inf')
        for x1, y1 in points:
            for x2, y2 in seen:
                if (x1, y2) in seen and (x2, y1) in seen:
                    area = abs(x1 - x2) * abs(y1 - y2)
                    if area and area < res:
                        res = area
            seen.add((x1, y1))

        if res != float('inf'):
            return res
        else:
            return 0


Solve in Python:
Given a side length `n`, traveling only right and down how many ways are there to get from the top left corner to the bottom right corner of an `n by n` grid?

Your mission is to write a program to do just that!

Add code to `route(n)` that returns the number of routes for a grid `n by n` (if n is less than 1 return 0).

Examples:

    -100 -> 0

    1 -> 2

    2 -> 6

    20 -> 137846528820

Note:
you're traveling on the edges of the squares in the grid not the squares themselves.

PS.If anyone has any suggestions of how to improve this kata please let me know.

from math import factorial as f
routes=lambda n:f(n*2) // (f(n)*f(n)) if n>0 else 0


Solve in Python:
Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).  For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.
When writing such an expression, we adhere to the following conventions:

The division operator (/) returns rational numbers.
There are no parentheses placed anywhere.
We use the usual order of operations: multiplication and division happens before addition and subtraction.
It's not allowed to use the unary negation operator (-).  For example, "x - x" is a valid expression as it only uses subtraction, but "-x + x" is not because it uses negation.

We would like to write an expression with the least number of operators such that the expression equals the given target.  Return the least number of operators used.

Example 1:
Input: x = 3, target = 19
Output: 5
Explanation: 3 * 3 + 3 * 3 + 3 / 3.  The expression contains 5 operations.

Example 2:

Input: x = 5, target = 501
Output: 8
Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.  The expression contains 8 operations.

Example 3:
Input: x = 100, target = 100000000
Output: 3
Explanation: 100 * 100 * 100 * 100.  The expression contains 3 operations.

Note:

2 <= x <= 100
1 <= target <= 2 * 10^8

class Solution:
    def leastOpsExpressTarget(self, x: int, target: int) -> int:
        @lru_cache(None)
        def calc(goal):
            if x == goal:
                return 0
            if x > goal:
                return min(goal*2 - 1, (x - goal) * 2)

            sums = x
            times = 0
            while sums < goal:
                times += 1
                sums *= x

            if sums == goal:
                return times

            if sums - goal < goal:
                return min(calc(sums - goal) + times + 1, calc(goal - (sums // x)) + times)

            return calc(goal - (sums // x)) + times

        return calc(target)


Solve in Python:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

# Definition for singly-linked list.
 # class ListNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.next = None

 class Solution:
     def reorderList(self, head):
         """
         :type head: ListNode
         :rtype: void Do not return anything, modify head in-place instead.
         """
         if not head:
             return None
         fast = slow = head
         temp = ListNode(0)
         while fast and fast.next:
             slow = slow.next
             fast = fast.next.next
         node = slow.next
         slow.next = None
         pre = None
         while node:
             cur = node.next
             node.next = pre
             pre = node
             node = cur
         first = head
         second = pre
         while first and second:
             node = first.next
             first.next = second
             second = second.next
             first.next.next = node
             first = node


Solve in Python:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

class Solution:
     def searchInsert(self, nums, target):
         """
         :type nums: List[int]
         :type target: int
         :rtype: int
         """
         left, right = 0, len(nums) - 1
         while left <= right:
             mid = left + (right - left) // 2
             if nums[mid] >= target:
                 right = mid - 1
             else:
                 left = mid + 1

         return left


Solve in Python:
Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.

Example 1:

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

Example 2:

Input: [3,3,7,7,10,11,11]
Output: 10

Note:
Your solution should run in O(log n) time and O(1) space.

class Solution:
     def singleNonDuplicate(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         res = 0
         for i in nums:
             res ^= i
         return res


def summary_ranges(a):
    a,i,li = sorted(set(a), key=a.index),0,[]
    while i < len(a):
        temp = [a[i]] ; i += 1
        while i < len(a) and temp[-1] + 1 == a[i] : temp.append(a[i]) ; i += 1
        li.append(temp)
    return [f"{i[0]}->{i[-1]}" if len(i) > 1 else f"{i[0]}" for i in li]


Solve in Python:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

# Definition for singly-linked list.
 # class ListNode:
 #     def __init__(self, x):
 #         self.val = x
 #         self.next = None

 class Solution:
     def deleteDuplicates(self, head):
         """
         :type head: ListNode
         :rtype: ListNode
         """
         if head == None:
             return None

         loop = head
         loop1 = head
         d = {}

         while loop:
             if loop.val in d.keys():
                 d[loop.val] += 1
             else:
                 d[loop.val] = 1
             loop = loop.next

         while loop1.next:
             if d[loop1.next.val] > 1:
                 loop1.next = loop1.next.next
             else:
                 loop1 = loop1.next

         if d[head.val] > 1:
             return head.next
         else:
             return head


Solve in Python:
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.

Example 1:

Input: nums = [1,3], n = 6
Output: 1
Explanation:
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.

Example 2:

Input: nums = [1,5,10], n = 20
Output: 2
Explanation: The two patches can be [2, 4].

Example 3:

Input: nums = [1,2,2], n = 5
Output: 0

class Solution:
     def minPatches(self, nums, n):
         """
         :type nums: List[int]
         :type n: int
         :rtype: int
         """
         res, cur, i = 0, 1, 0
         while cur <= n:
             if i < len(nums) and nums[i] <= cur:
                 cur += nums[i]
                 i += 1
             else:
                 cur *= 2
                 res += 1
         return res


Solve in Python:
Given a square array of integers A, we want the minimum sum of a falling path through A.
A falling path starts at any element in the first row, and chooses one element from each row.  The next row's choice must be in a column that is different from the previous row's column by at most one.

Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: 12
Explanation:
The possible falling paths are:

[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]
[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]
[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]

The falling path with the smallest sum is [1,4,7], so the answer is 12.

Constraints:

1 <= A.length == A[0].length <= 100
-100 <= A[i][j] <= 100

class Solution:
    def minFallingPathSum(self, A: List[List[int]]) -> int:
        dp = [A[0][:], [0 for _ in A[0]]]
        for i in range(1, len(A)):
            for j in range(len(A[i])):
                dp[i & 1][j] = min([dp[(i - 1) & 1][j + k] for k in (-1, 0, 1) if 0 <= j + k < len(A[i])]) + A[i][j]
        return min(dp[(len(A) - 1) & 1])


Solve in Python:
Given a square grid of integers arr, a falling path with non-zero shifts is a choice of exactly one element from each row of arr, such that no two elements chosen in adjacent rows are in the same column.
Return the minimum sum of a falling path with non-zero shifts.

Example 1:
Input: arr = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
Explanation:
The possible falling paths are:
[1,5,9], [1,5,7], [1,6,7], [1,6,8],
[2,4,8], [2,4,9], [2,6,7], [2,6,8],
[3,4,8], [3,4,9], [3,5,7], [3,5,9]
The falling path with the smallest sum is [1,5,7], so the answer is 13.

Constraints:

1 <= arr.length == arr[i].length <= 200
-99 <= arr[i][j] <= 99

class Solution:
    def minFallingPathSum(self, arr: List[List[int]]) -> int:

        # [[1,2,3],
        #  [4,5,6],
        #  [7,8,9]]

        # do a dp where dp(i,j) returns the minimum path starting from (i,j)

        if not arr:
            return 0

        m = len(arr)
        n = len(arr[0])
        INF = float('inf')
        dp = [[INF]*n for _ in range(m)]

        dp[-1] = arr[-1]

        for i in range(m-2,-1,-1):
            for j in range(n):
                dp[i][j] = min(dp[i+1][:j]+dp[i+1][j+1:])+arr[i][j]
        print(dp)
        return min(dp[0])


Solve in Python:
Given a square matrix (i.e. an array of subarrays), find the sum of values from the first value of the first array, the second value of the second array, the third value of the third array, and so on...

## Examples

```
array = [[1, 2],
         [3, 4]]

diagonal sum: 1 + 4 = 5
```

```
array = [[5, 9, 1, 0],
         [8, 7, 2, 3],
         [1, 4, 1, 9],
         [2, 3, 8, 2]]

diagonal sum: 5 + 7 + 1 + 2 = 15
```

def diagonal_sum(array):
    return sum(row[i] for i, row in enumerate(array))


Solve in Python:
Given a square matrix of size N×N, calculate the absolute difference between the sums of its diagonals.

-----Input-----
The first line contains a single integer N. The next N lines denote the matrix's rows, with each line containing N space-separated integers describing the columns.

-----Output-----
Print the absolute difference between the two sums of the matrix's diagonals as a single integer.

-----Constraints-----
1<=N<=10

-----Example-----
Input:
3
11 2 4
4 5 6
10 8 -12

Output:
15

-----Explanation-----
The primary diagonal is:
11
5
-12
Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:
4
5
10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15

def diagonal_difference(matrix):
 l = sum(matrix[i][i] for i in range(N))
 r = sum(matrix[i][N-i-1] for i in range(N))
 return abs(l - r)

matrix = []
N = eval(input())
for _ in range(N):
 matrix.append(list(map(int, input().split())))

print(diagonal_difference(matrix))


Solve in Python:
Given a standard english sentence passed in as a string, write a method that will return a sentence made up of the same words, but sorted by their first letter. However, the method of sorting has a twist to it:
* All words that begin with a lower case letter should be at the beginning of the sorted sentence, and sorted in ascending order.
* All words that begin with an upper case letter should come after that, and should be sorted in descending order.

If a word appears multiple times in the sentence, it should be returned multiple times in the sorted sentence. Any punctuation must be discarded.

## Example

For example, given the input string `"Land of the Old Thirteen! Massachusetts land! land of Vermont and Connecticut!"`, your method should return `"and land land of of the Vermont Thirteen Old Massachusetts Land Connecticut"`. Lower case letters are sorted `a -> l -> l -> o -> o -> t` and upper case letters are sorted `V -> T -> O -> M -> L -> C`.

def pseudo_sort(s):
    s = ''.join(i for i in s if i.isalpha() or i is ' ')
    a =  sorted(i for i in s.split() if i[0].islower())
    b =  sorted((i for i in s.split() if i[0].isupper()),key=lambda x: x.lower(),reverse=True)
    return ' '.join(a+b)


Solve in Python:
Given a string $s$.
You can perform the following operation on given string any number of time.
Delete two successive elements of the string if they are same.
After performing the above operation you have to return the least possible length of the string.

-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, a string $s$.

-----Output:-----
For each testcase, output in a single line answer- minimum length of string possible after performing given operations.

-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq length of string \leq 10^5$
$s$ contains only lowercase letters.

-----Sample Input:-----
3
abccd
abbac
aaaa

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

-----EXPLANATION:-----
- In first case, $"abd"$ will be final string.
- in second case, $"c"$ will be final string

for _ in range(int(input())):
    inps = input().strip()
    stck = [inps[0]]
    for i in range(1, len(inps)):
        if len(stck) > 0:
            if inps[i] == stck[-1]:
                stck.pop()
            else:
                stck.append(inps[i])
        else:
            stck.append(inps[i])
    print(len(stck))


Solve in Python:
Given a string (`str`) containing a base-10 integer between `0` and `10000`, convert the integer to its binary representation. At that point, obtain a count of the maximum amount of consecutive 0s. From there, return the count in written form with a capital letter.

In the very first example, we have an argument of `"9"` which is being passed to the method. The binary representation of `9` is `1001` which can be read as: one, zero, zero, one. There are, at most, two consecutive 0s, resulting in the integer `2` as the value of the count. The output in the block of code above reflects the final step of taking `2` from standard form to the written form `"Two"` as prompted.

In the very last example, we have an argument of `"550"` which is being passed to the method. The binary representation of `550` is `1000100110` which can be read as: one, zero, zero, zero, one, zero, zero, one, one, zero. There are, at most, three consecutive 0s, resulting in the integer `3` as the value of the count. The output in the block of code above reflects the final step of taking `3` from standard form to the written form of `"Three"` as prompted.

One way, among many, to visualize the end of each step might look like:
```
max_consec_zeros("777")
1: "777"
2: 777
3: 1100001001
4: 4
5: "Four"
max_consec_zeros("777") => "Four"
```
Happy coding!

import re
ls = ["Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen"]
def max_consec_zeros(n):
    return ls[max(map(lambda x:len(x),re.findall(r'0*',bin(int(n))[2:])))]


Solve in Python:
Given a string S and a string T, count the number of distinct subsequences of S which equals T.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Example 1:

Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:

As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)

rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^

Example 2:

Input: S = "babgbag", T = "bag"
Output: 5
Explanation:

As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)

babgbag
^^ ^
babgbag
^^    ^
babgbag
^    ^^
babgbag
  ^  ^^
babgbag
    ^^^

class Solution:
     def __init__(self):
         self.dp = {}
         self.s = ""
         self.t = ""
         self.letter2Indices = {}

     def numDistinct(self, s, t):
         """
         :type s: str
         :type t: str
         :rtype: int
         """
         if len(s) < len(t):
             return 0
         if not t:
             return 1

         self.s = s.lower()
         self.t = t.lower()
         length = len(s)
         for i in range(len(t)):
             self.dp[i] = [-1] * length
         for i in range(length):
             letter = self.s[i]
             if letter in self.letter2Indices:
                 self.letter2Indices[letter].append(i)
             else:
                 self.letter2Indices[letter] = list([i])

         return self.numSubseq(0, 0)

     def numSubseq(self, startS, startT):
         if startT >= len(self.t):
             return 1
         if startS >= len(self.s):
             return 0

         if self.dp[startT][startS] >= 0:
             return self.dp[startT][startS]

         letter = self.t[startT]
         count = 0
         firstMatch = -1
         if letter in self.letter2Indices:
             for i in self.letter2Indices[letter]:
                 if i >= startS:
                     count += self.numSubseq(i+1, startT+1)
                     if firstMatch < 0:
                         # We can directly fill dp[startT][startS:firstMatch-1] with the same number
                         firstMatch = i

         self.dp[startT][startS] = count
         for i in range(startS + 1, firstMatch):
             self.dp[startT][i] = count
         return count


Solve in Python:
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

       If there is no such window in S that covers all characters in T, return the empty string "".
       If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

class Solution:
     def minWindow(self, s, t):
         """
         :type s: str
         :type t: str
         :rtype: str
         """
         table = {}
         for c in t:
             table[c] = table[c] + 1 if c in table else 1
         start, end, count = 0, 0, len(t)
         min_start, min_end = None, None
         for i in range(len(s)):
             if s[i] in table:
                 if table[s[i]] > 0:
                     count -= 1
                 table[s[i]] -= 1
             if count == 0:
                 while count == 0:
                     if s[start] in table:
                         if table[s[start]] >= 0:
                             count += 1
                             if min_start == None or i - start < min_end - min_start:
                                 min_start, min_end = start, i
                         table[s[start]] += 1
                     start += 1
         if min_start == None:
             return ""
         else:
             return s[min_start:(min_end + 1)]

         '''
         def check(m, n, mode=1):
             table = dict(zip(t, [0]*len(t)))
             for i in range(m, n+1):
                 if s[i] in table:
                     if mode == 1 and table[s[i]] != None:
                         continue
                     else:
                         table[s[i]] = i

             a, b = None, None
             for k, v in table.items():
                 if v == None:
                     return 0, 0, False
                 if a == None or a > v:
                     a = v
                 if b == None or b < v:
                     b = v
             return a, b, True

         first, last, result = check(0, len(s)-1, 1)
         if not result:
             return False
         a, b = first, last
         for i in range(last+1, len(s)):
             t_a, t_b, result = check(i-(b-a+1), i, 2)
             if result == True:
                 a, b = t_a, t_b

         return s[a:(b+1)]
         '''


Solve in Python:
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique.

Example 1:
Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Note:

1 <= S.length <= 20000
S consists only of English lowercase letters.

class Solution:
    def removeDuplicates(self, S: str) -> str:
        count = 1
        S = list(S)
        while count != 0:
            x = 0
            while x < (len(S) - 1):
                if S[x] == S[x + 1]:
                    S.pop(x)
                    S.pop(x)
                    if x > 0:
                        x -= 1
                    count += 1
                x += 1
            if count > 1:
                count = 1
            else:
                count = 0
        return(''.join(S))


Solve in Python:
Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times.  (The occurrences may overlap.)
Return any duplicated substring that has the longest possible length.  (If S does not have a duplicated substring, the answer is "".)

Example 1:
Input: "banana"
Output: "ana"

Example 2:
Input: "abcd"
Output: ""

Note:

2 <= S.length <= 10^5
S consists of lowercase English letters.

class Solution:
    def longestDupSubstring(self, S):
        nums = [ord(c) - ord('a') for c in S]
        #BASE, MOD = 113, 1000000007
        BASE, MOD = 26, 2**32
        def check(L):
            cur_hash, seen = 0, set()
            for val in nums[:L]:
                cur_hash = ((cur_hash * BASE) + val) % MOD
            seen.add(cur_hash)
            X = pow(BASE, L-1, MOD) # (BASE ** (L-1)) % MOD
            for i, val in enumerate(nums[L:]):
                # cur_hash -= nums[i] * (BASE ** (L-1))
                cur_hash -= nums[i] * X
                cur_hash = ((cur_hash * BASE) + val) % MOD
                if cur_hash in seen:
                    return i + 1
                seen.add(cur_hash)
            return -1
        low, high = 1, len(S)
        res = 0
        while low < high:
            mid = (low + high)//2
            idx = check(mid)
            if idx != -1:
                low = mid + 1
                res = idx
            else:
                high = mid
        return S[res: res + low-1]

        #while low <= high:
        #    mid = (low + high)//2
        #    idx = check(mid)
        #    if idx != -1:
        #        low = mid + 1
        #        res = idx
        #    else:
        #        high = mid - 1
        #return S[res: res + low-1]


Solve in Python:
Given a string S, count the number of distinct, non-empty subsequences of S .
Since the result may be large, return the answer modulo 10^9 + 7.

Example 1:
Input: "abc"
Output: 7
Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".

Example 2:
Input: "aba"
Output: 6
Explanation: The 6 distinct subsequences are "a", "b", "ab", "ba", "aa" and "aba".

Example 3:
Input: "aaa"
Output: 3
Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".

Note:

S contains only lowercase letters.
1 <= S.length <= 2000

class Solution:
    def distinctSubseqII(self, S: str) -> int:
        MOD = 10 ** 9 + 7
        n = len(S)
        dp = collections.Counter()
        result = 0
        for i in range(n - 1, -1, -1):
            old = result
            result = (2 * old + 1 - dp[S[i]]) % MOD
            dp[S[i]] += result - old
        return result


Solve in Python:
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

Example 1:
Input: "ab-cd"
Output: "dc-ba"

Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

Note:

S.length <= 100
33 <= S[i].ASCIIcode <= 122
S doesn't contain \ or "

class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        a={}
        j=0
        s=list(s)
        i=0
        while i<len(s):
            if not s[i].isalpha():
                a[i+j]=s[i]
                del s[i]
                j+=1
            else:
                i+=1
        s=s[::-1]
        for i in a:
            s.insert(i,a[i])
        return ''.join(s)


Solve in Python:
Given a string S.
You have to return another string such that even-indexed and odd-indexed characters of S are grouped and groups are space-separated (see sample below)

Note:
0 is considered to be an even index.
All input strings are valid with no spaces

input:
'CodeWars'

output
'CdWr oeas'

S[0] = 'C'
S[1] = 'o'
S[2] = 'd'
S[3] = 'e'
S[4] = 'W'
S[5] = 'a'
S[6] = 'r'
S[7] = 's'

Even indices 0, 2, 4, 6, so we have 'CdWr' as the first group
odd ones are 1, 3, 5, 7, so the second group is 'oeas'
And the final string to return is 'Cdwr oeas'

Enjoy.

def sort_my_string(s):
    return '{} {}'.format(s[::2], s[1::2])


Solve in Python:
Given a string S of digits, such as S = "123456579", we can split it into a Fibonacci-like sequence [123, 456, 579].
Formally, a Fibonacci-like sequence is a list F of non-negative integers such that:

0 <= F[i] <= 2^31 - 1, (that is, each integer fits a 32-bit signed integer type);
F.length >= 3;
and F[i] + F[i+1] = F[i+2] for all 0 <= i < F.length - 2.

Also, note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.
Return any Fibonacci-like sequence split from S, or return [] if it cannot be done.
Example 1:
Input: "123456579"
Output: [123,456,579]

Example 2:
Input: "11235813"
Output: [1,1,2,3,5,8,13]

Example 3:
Input: "112358130"
Output: []
Explanation: The task is impossible.

Example 4:
Input: "0123"
Output: []
Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.

Example 5:
Input: "1101111"
Output: [110, 1, 111]
Explanation: The output [11, 0, 11, 11] would also be accepted.

Note:

1 <= S.length <= 200
S contains only digits.

class Solution:
    def splitIntoFibonacci(self, S: str) -> List[int]:
        if len(S) < 3: return []
        for i in range(1, len(S) - 2):
            first = S[:i]
            for j in range(i, len(S) - 1):
                j += 1
                second = S[i:j]
                split = self.dfs(first, second, S[j:], [first, second])
                if split: return split

        return []

    def notvalid(self, s):
        if int(s) != 0 and s[0] == 0:
            return True
        if int(s) > 2**31 - 1:
            return True
        return False

    def dfs(self, s1, s2, rem, seq):
        s3 = str(int(s1) + int(s2))
        if self.notvalid(s3): return []
        l = len(s3)
        if rem[:l] == s3:
            seq.append(s3)
            if len(rem) > l:
                return self.dfs(s2, s3, rem[l:], seq)
            else:
                return seq
        return []


Solve in Python:
Given a string `S` and a character `C`, return an array of integers representing the shortest distance from the current character in `S` to `C`.

### Notes

* All letters will be lowercase.
* If the string is empty, return an empty array.
* If the character is not present, return an empty array.

## Examples

```python
shortest_to_char("lovecodewars", "e") == [3, 2, 1, 0, 1, 2, 1, 0, 1, 2, 3, 4]
shortest_to_char("aaaabbbb", "b") == [4, 3, 2, 1, 0, 0, 0, 0]
shortest_to_char("", "b") == []
shortest_to_char("abcde", "") == []
```

___

If you liked it, please rate  :D

import re

def shortest_to_char(s, c):
    if not c or c not in s:
        return []
    positions = [m.start() for m in re.finditer(c, s)]
    return [min(abs(p - i) for p in positions) for i in range(len(s))]


Solve in Python:
Given a string ``string`` that contains only letters, you have to find out the number of **unique** strings (including ``string`` itself) that can be produced by re-arranging the letters of the ``string``.  Strings are case **insensitive**.

HINT: Generating all the unique strings and calling length on that isn't a great solution for this problem. It can be done a lot faster...

## Examples

```python
uniqcount("AB") = 2      # "AB", "BA"
uniqcount("ABC") = 6     # "ABC", "ACB", "BAC", "BCA", "CAB", "CBA"
uniqcount("ABA") = 3     # "AAB", "ABA", "BAA"
uniqcount("ABBb") = 4    # "ABBB", "BABB", "BBAB", "BBBA"
uniqcount("AbcD") = 24   # "ABCD", etc.
```

from collections import Counter
from functools import reduce
from math import factorial
from operator import mul

def uniq_count(string):
    return factorial(len(string)) // reduce(mul, map(factorial, Counter(string.lower()).values()), 1)


Solve in Python:
Given a string `s` of uppercase letters, your task is to determine how many strings `t` (also uppercase) with length equal to that of `s` satisfy the followng conditions:

* `t` is lexicographical larger than `s`, and
* when you write both `s` and `t` in reverse order, `t` is still lexicographical larger than `s`.

```Haskell
For example:
solve('XYZ') = 5. They are: YYZ, ZYZ, XZZ, YZZ, ZZZ
```
String lengths are less than `5000`. Return you answer `modulo 10^9+7 (= 1000000007)`.

More examples in test cases. Good luck!

def solve(s):
    val = [90 - ord(c) for c in reversed(s)]
    tmp, res = [0], val[0]
    for v1,v2 in zip(val, val[1:]):
        tmp.append(tmp[-1]*26 + v1)
        res += v2 * (tmp[-1]+1)
    return res % (10**9+7)


Solve in Python:
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

Example 1:

Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

Output:
"apple"

Example 2:

Input:
s = "abpcplea", d = ["a","b","c"]

Output:
"a"

Note:

All the strings in the input will only contain lower-case letters.
The size of the dictionary won't exceed 1,000.
The length of all the strings in the input won't exceed 1,000.

class Solution:
     def findLongestWord(self, s, d):
         """
         :type s: str
         :type d: List[str]
         :rtype: str
         """
         word_dict = collections.defaultdict(list)
         for i, word in enumerate(d):
             word_dict[word[0]].append((i, word))

         res = ""
         for c in s:
             words_startswithc = word_dict[c]
             word_dict[c] = []
             for i, word in words_startswithc:
                 if len(word)==1:
                     if len(d[i])==len(res):
                         res = min(res, d[i])
                     else: res = d[i] if len(d[i])>len(res) else res
                 else:
                     word_dict[word[1]].append((i, word[1:]))
         return res


Solve in Python:
Given a string and an array of index numbers, return the characters of the string rearranged to be in the order specified by the accompanying array.

Ex:

scramble('abcd', [0,3,1,2]) -> 'acdb'

The string that you will be returning back will have: 'a' at index 0, 'b' at index 3, 'c' at index 1, 'd' at index 2, because the order of those characters maps to their corisponding numbers in the index array.

In other words, put the first character in the string at the index described by the first element of the array

You can assume that you will be given a string and array of equal length and both containing valid characters (A-Z, a-z, or 0-9).

def scramble(string, array):
    return "".join(v for _, v in sorted(zip(array, string)))


Solve in Python:
Given a string and an array of integers representing indices, capitalize all letters at the given indices.

For example:

* `capitalize("abcdef",[1,2,5]) = "aBCdeF"`
* `capitalize("abcdef",[1,2,5,100]) = "aBCdeF"`. There is no index 100.

The input will be a lowercase string with no spaces and an array of digits.

Good luck!

Be sure to also try:

[Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075)

[String array revisal](https://www.codewars.com/kata/59f08f89a5e129c543000069)

def capitalize(s,ind):
    a = ""
    for i in range(len(s)):
        if i in ind:
            a = a + s[i].upper()
        else:
            a += s[i]
    return a


Solve in Python:
Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Restrictions:

 The string consists of lower English letters only.
 Length of the given string and k will in the range [1, 10000]

class Solution:
     def reverseStr(self, s, k):
         """
         :type s: str
         :type k: int
         :rtype: str
         """

         i = 0
         tmp = 0
         ret = ""
         while i < len(s):
             if len(s)-i < k:
                 tmp = len(s)-i
             else:
                 tmp = k
             ttmp = tmp
             while ttmp!= 0:
                 ret += s[i+ttmp-1]
                 ttmp -= 1

             i+=tmp
             if len(s)-i < k:
                 tmp = len(s)-i
             else:
                 tmp = k
             ttmp = tmp

             while ttmp!= 0:
                 ret += s[i]
                 i+=1
                 ttmp -= 1

         return ret


Solve in Python:
Given a string as input, move all of its vowels to the end of the string, in the same order as they were before.

Vowels are (in this kata): `a, e, i, o, u`

Note: all provided input strings are lowercase.

## Examples
```python
"day"    ==>  "dya"
"apple"  ==>  "pplae"
```

def move_vowels(input):
    return "".join(sorted(input, key=lambda c: c in "aeiou"))


Solve in Python:
Given a string consisting of only lowercase English alphabets, your task is to find the smallest palindromic substring.
In case there are multiple palindromic substrings of the same length present, print the lexicographically smallest substring.
Formally, a substring is a contiguous sequence of characters within a string. So in a string "abcdef", "abc" is a substring whereas "adf" is not a substring.
A palindrome is a word, phrase, or sequence that reads the same backwards as forwards, e.g. madam or mom.

-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains of two lines of input, two integers.
- First, we have a single integer $N$ which signifies the length of the substring.
- Next, we have a string of length $N$ that only has lowercase English alphabets.

-----Output:-----
For each testcase, output in a single line the shortest palindromic substring.

-----Constraints-----
- $1 \leq T \leq 100$
- $2 \leq N \leq 10^5$

-----Sample Input:-----
2
2
zy
1
cd

-----Sample Output:-----
y
c

-----EXPLANATION:-----
There are only two possibilities. "z" and "y". Since both of them have the same length. We print the lexicographically smaller substring which is y.

# cook your dish here
try:
 t=int(input())
 for i in range(t):
  n=int(input())
  strin=input()
  l=list(strin)

  l.sort()
  print(l[0])
except:
 pass


Solve in Python:
Given a string containing a list of integers separated by commas, write the function string_to_int_list(s) that takes said string and returns a new list containing all integers present in the string, preserving the order.

For example, give the string "-1,2,3,4,5", the function string_to_int_list() should return [-1,2,3,4,5]

Please note that there can be one or more consecutive commas whithout numbers, like so: "-1,-2,,,,,,3,4,5,,6"

def string_to_int_list(s):
    return [int(n) for n in s.split(",") if n]


Solve in Python:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

       Open brackets must be closed by the same type of brackets.
       Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

class Solution:

     import re

     def isValid(self, s):
         """
         :type s: str
         :rtype: bool
         """

         while(s!=""):
             len_orig = len(s)
             s = s.replace('()', '')
             s = s.replace('[]', '')
             s = s.replace('{}', '')
             if len(s) == len_orig:
                 return False

         return True


Solve in Python:
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:

Any left parenthesis '(' must have a corresponding right parenthesis ')'.
Any right parenthesis ')' must have a corresponding left parenthesis '('.
Left parenthesis '(' must go before the corresponding right parenthesis ')'.
'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
An empty string is also valid.

Example 1:

Input: "()"
Output: True

Example 2:

Input: "(*)"
Output: True

Example 3:

Input: "(*))"
Output: True

Note:

The string size will be in the range [1, 100].

class Solution:
     def checkValidString(self, s):
         """
         :type s: str
         :rtype: bool
         """
         a=0
         b=0
         for i in range(len(s)) : #
             if s[i]== "*" : # The case of *
                 a = a+1 #To account for its possibility to be the opening of a brace pair
                 if b>0 : #To accout for its possibility to be the closing of a pair
                     b = b-1

             elif s[i]=="(" : #For each open brace you see, increment a and b (marking the potential to make a pair)
                 a = a+1
                 b = b+1

             elif s[i]==")" :
                 a = a-1 #For each ) brace, decrement a - marking one complete pair.
                 if b>0 : #This check is to ensure the terminating check - b==0 i.e. each ( has a pairing ).
                     b = b-1

             if a<0 : # If at any point the number of closing braces are more than opening braces, terminate
                 return False

         if b==0 : # If the number of pairs are balanced, return true
             return True
         else :
             return False


Solve in Python:
Given a string made up of letters a, b, and/or c, switch the position of letters a and b (change a to b and vice versa). Leave any incidence of c untouched.

Example:

'acb' --> 'bca'
'aabacbaa' --> 'bbabcabb'

def switcheroo(string):
    #your code here
    result = ''
    for letter in string:
        if letter == 'a':
            letter = 'b'
        elif letter == 'b':
            letter = 'a'
        result += letter
    return result


Solve in Python:
Given a string num representing the digits of a very large integer and an integer k.
You are allowed to swap any two adjacent digits of the integer at most k times.
Return the minimum integer you can obtain also as a string.

Example 1:

Input: num = "4321", k = 4
Output: "1342"
Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.

Example 2:
Input: num = "100", k = 1
Output: "010"
Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.

Example 3:
Input: num = "36789", k = 1000
Output: "36789"
Explanation: We can keep the number without any swaps.

Example 4:
Input: num = "22", k = 22
Output: "22"

Example 5:
Input: num = "9438957234785635408", k = 23
Output: "0345989723478563548"

Constraints:

1 <= num.length <= 30000
num contains digits only and doesn't have leading zeros.
1 <= k <= 10^9

class Solution:
    def minInteger(self, num: str, k: int) -> str:
        n=len(num)
        if k<=0:
            return num

        if k>n*(n-1)//2:
            return ''.join(sorted(list(num)))

        for i in range(10):
            idx = num.find(str(i))
            if idx>=0 and idx<=k:
                return num[idx]+self.minInteger(num[:idx]+num[idx+1:],k-idx)


Solve in Python:
Given a string of characters, I want the function `findMiddle()`/`find_middle()` to return the middle number in the product of each digit in the string.

Example: 's7d8jd9' -> 7, 8, 9 -> 7\*8\*9=504, thus 0 should be returned as an integer.

Not all strings will contain digits. In this case and the case for any non-strings, return -1.

If the product has an even number of digits, return the middle two digits

Example: 1563 -> 56

NOTE: Remove leading zeros if product is even and the first digit of the two is a zero.
Example 2016 -> 1

def find_middle(string):
    if not type(string) == str:
        return -1
    numbers = [int(i) for i in string if i.isdigit()]
    if not numbers:
        return -1
    prod = 1
    for i in numbers:
        prod *= i
    prod_str = str(prod)
    return int(prod_str[(len(prod_str) // 2) - 1:(len(prod_str) // 2) + 1]) if len(prod_str) % 2 == 0 else int(prod_str[len(prod_str)//2])


Solve in Python:
Given a string of integers, count how many times that integer repeats itself, then return a string showing the count and the integer.

Example: `countMe('1123')` (`count_me` in Ruby)

- Here 1 comes twice so `` will be `"21"`
- then 2 comes once so `` will be `"12"`
- then 3 comes once so `` will be `"13"`

hence output string will be `"211213"`.

Similarly `countMe('211213')` will return `'1221121113'`
(1 time 2, 2 times 1, 1 time 2, 1 time 1, 1 time 3)

Return `""` for empty, nil or non numeric strings

from itertools import groupby

def count_me(data):
    return "".join(f"{len(list(g))}{k}" for k, g in groupby(data)) if data.isdecimal() else ""


Solve in Python:
Given a string of integers, return the number of odd-numbered substrings that can be formed.

For example, in the case of `"1341"`, they are `1, 1, 3, 13, 41, 341, 1341`, a total of `7` numbers.

`solve("1341") = 7`.  See test cases for more examples.

Good luck!

If you like substring Katas, please try

[Longest vowel chain](https://www.codewars.com/kata/59c5f4e9d751df43cf000035)

[Alphabet symmetry](https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0)

def solve(s):
    return sum(len(s)- i for i,j in enumerate(s[::-1]) if int(j)%2==1)


Solve in Python:
Given a string of words (x), you need to return an array of the words, sorted alphabetically by the final character in each.

If two words have the same last letter, they returned array should show them in the order they appeared in the given string.

All inputs will be valid.

last=lambda x: sorted(x.split(), key=lambda i: i[-1])


Solve in Python:
Given a string of words and numbers. Extract the expression including:
1. the operator: either addition or subtraction
2. the two numbers that we are operating on

Return the result of the calculation.

Example:

"Panda has 48 apples and loses 4" returns 44

"Jerry has 34 apples and gains 6" returns 40

"loses" and "gains" are the only two words describing operators.

Should be a nice little kata for you :)

Note:
No fruit debts nor bitten apples = The numbers are integers and no negatives

import re
def calculate(string):
    return eval(re.sub("[^\d+-]", "", string.replace("loses", "-").replace("gains", "+")) )


Solve in Python:
Given a string of words, you need to find the highest scoring word.

Each letter of a word scores points according to its position in the alphabet: `a = 1, b = 2, c = 3` etc.

You need to return the highest scoring word as a string.

If two words score the same, return the word that appears earliest in the original string.

All letters will be lowercase and all inputs will be valid.

alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m',
            'n','o','p','q','r','s','t','u','v','w','x','y','z']

def high(x):

  strings = list(x.split())
  array = []

  for word in strings:
    value = 0
    for letter in word:
      value += alphabet.index(letter)+1
    array.append([value, word])
  array.sort()
  return array[-1][1]


Solve in Python:
Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:

The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.
A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.
A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.
A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid.
A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.
A < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME  (not necessarily valid).
The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>.
CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.

Valid Code Examples:

Input: "
This is the first line <![CDATA[
]]>
"
Output: True
Explanation:
The code is wrapped in a closed tag :
 and
.
The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata.
Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, it should be considered as...

class Solution:
     def isValid(self, code):
         """
         :type code: str
         :rtype: bool
         """
         S=code
         CDATA_BEGIN='![CDATA['
         CDATA_END=']]>'

         def collect_tag(i):

             for j in range(i,len(S)):
                 if S[j]=='>':
                     break
             else:
                     return None
             return S[i+1:j]

         def valid_tag(tag):
             if 1<=len(tag)<=9 and all('A' <=c<= 'Z'  for c in tag):
                 return True
             else:
                 return False

         if not S or S[0]!='<':
             return False
         #print('###########1111############')
         tag=collect_tag(0)
         #print(tag)
         if not tag or not S.startswith('<{}>'.format(tag)) or not S.endswith('</{}>'.format(tag)) or not valid_tag(tag):

             return False

         S=S[len(tag)+2:-len(tag)-3]

         i=0
         stack=[]

         while i<len(S):

             if S[i]=='<':
                 tag=collect_tag(i)
                 #print(tag)
                 if not tag:

                     return False

                 if tag.startswith(CDATA_BEGIN):
                     while i<len(S)  and S[i:i+3]!=CDATA_END:
                         i+=1
                     if S[i:i+3]!=CDATA_END:
                         return False
                     i+=2
                 elif tag.startswith('/'):
                     tag=tag[1:]
                     if  not valid_tag(tag) or not stack or stack.pop()!=tag:
                         return False
                 else:
                     if not valid_tag(tag):
                         return False
                     stack.append(tag)

             i+=1
         return not stack


Solve in Python:
Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not).

Example 1:
s = "abc", t = "ahbgdc"

Return true.

Example 2:
s = "axc", t = "ahbgdc"

Return false.

Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?

Credits:Special thanks to @pbrother for adding this problem and creating all test cases.

class Solution:
     def isSubsequence(self, s, t):
         t = iter(t)
         return all(c in t for c in s)


Solve in Python:
Given a string s and an integer k.
Return the maximum number of vowel letters in any substring of s with length k.
Vowel letters in English are (a, e, i, o, u).

Example 1:
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.

Example 2:
Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.

Example 3:
Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.

Example 4:
Input: s = "rhythms", k = 4
Output: 0
Explanation: We can see that s doesn't have any vowel letters.

Example 5:
Input: s = "tryhard", k = 4
Output: 1

Constraints:

1 <= s.length <= 10^5
s consists of lowercase English letters.
1 <= k <= s.length

class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        vowels = {'a','e','i','o','u'}
        vowel_count = 0
        for i in range(k):
            if s[i] in vowels:
                vowel_count += 1

        max_vowels = vowel_count

        for i in range(k, len(s)):
            if s[i-k] in vowels:
                vowel_count -= 1
            if s[i] in vowels:
                vowel_count += 1
            max_vowels = vowel_count if vowel_count > max_vowels else max_vowels

        return max_vowels


Solve in Python:
Given a string s and an integer k. You should construct k non-empty palindrome strings using all the characters in s.
Return True if you can use all the characters in s to construct k palindrome strings or False otherwise.

Example 1:
Input: s = "annabelle", k = 2
Output: true
Explanation: You can construct two palindromes using all characters in s.
Some possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"

Example 2:
Input: s = "leetcode", k = 3
Output: false
Explanation: It is impossible to construct 3 palindromes using all the characters of s.

Example 3:
Input: s = "true", k = 4
Output: true
Explanation: The only possible solution is to put each character in a separate string.

Example 4:
Input: s = "yzyzyzyzyzyzyzy", k = 2
Output: true
Explanation: Simply you can put all z's in one string and all y's in the other string. Both strings will be palindrome.

Example 5:
Input: s = "cr", k = 7
Output: false
Explanation: We don't have enough characters in s to construct 7 palindromes.

Constraints:

1 <= s.length <= 10^5
All characters in s are lower-case English letters.
1 <= k <= 10^5

from collections import defaultdict

class Solution:

    def canConstruct(self, s: str, k: int) -> bool:
        d = defaultdict(int)
        if len(s) < k:
            return False

        for char in s:
            d[char] += 1

        odd = 0
        for key in d:
            if d[key] % 2 != 0:

                odd += 1

        return odd <= k


Solve in Python:
Given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string, if it is generated by deleting some characters of a given string without changing its order.
A string is called palindrome if is one that reads the same backward as well as forward.

Example 1:
Input: s = "ababa"
Output: 1
Explanation: String is already palindrome

Example 2:
Input: s = "abb"
Output: 2
Explanation: "abb" -> "bb" -> "".
Remove palindromic subsequence "a" then "bb".

Example 3:
Input: s = "baabb"
Output: 2
Explanation: "baabb" -> "b" -> "".
Remove palindromic subsequence "baab" then "b".

Example 4:
Input: s = ""
Output: 0

Constraints:

0 <= s.length <= 1000
s only consists of letters 'a' and 'b'

class Solution:
    def removePalindromeSub(self, s: str) -> int:
        if not s:
            return 0
        if s == s[::-1]:
            return 1
        else:
            return 2


Solve in Python:
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

Input: "Hello World"
Output: 5

class Solution:
     def lengthOfLastWord(self, s):
         """
         :type s: str
         :rtype: int
         """
         v = s.split()
         if not v:
             return 0
         else:
             return len(v[-1])


Solve in Python:
Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:

0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.

To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.

Example 1:
Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".

Example 2:
Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""

Example 3:
Input: s = "s"
Output: "s"

Constraints:

1 <= s.length <= 100
s contains only lower and upper case English letters.

class Solution:
    def makeGood(self, s: str) -> str:

        stack=[]

        for i in s:
            if (stack!=[] and i.lower()==stack[-1].lower() and i!=stack[-1] ) :
                stack.pop()
            else:
                stack.append(i)
        return ''.join(stack)


Solve in Python:
Given a string s, determine if it is valid.
A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times:

Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be empty.

Return true if s is a valid string, otherwise, return false.

Example 1:
Input: s = "aabcbc"
Output: true
Explanation:
"" -> "abc" -> "aabcbc"
Thus, "aabcbc" is valid.
Example 2:
Input: s = "abcabcababcc"
Output: true
Explanation:
"" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"
Thus, "abcabcababcc" is valid.

Example 3:
Input: s = "abccba"
Output: false
Explanation: It is impossible to get "abccba" using the operation.

Example 4:
Input: s = "cababc"
Output: false
Explanation: It is impossible to get "cababc" using the operation.

Constraints:

1 <= s.length <= 2 * 104
s consists of letters 'a', 'b', and 'c'

class Solution:
    def isValid(self, s: str) -> bool:
        while s.find('abc') > -1:
            i = s.find('abc')
            s = s[:i] + s[i+3:]
        return s == ''


Solve in Python:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

class Solution:
     def longestPalindrome(self, s):
         """
         :type s: str
         :rtype: str
         """
         if len(s) == 0:
             return 0
         start = 0
         maxlength = 1
         for i in range(len(s)):
             if i - maxlength  - 1 >= 0 and s[i-maxlength-1:i+1] == s[i-maxlength-1:i+1][::-1]:
                 start = i-maxlength-1
                 maxlength+=2
             if i-maxlength>=0 and s[i-maxlength:i+1]==s[i-maxlength:i+1][::-1]:
                 start = i-maxlength
                 maxlength+=1
         return s[start:start+maxlength]


Solve in Python:
Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

Example:

Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.

class Solution:
     def minCut(self, s):
         """
         :type s: str
         :rtype: int
         """
         if s == s[::-1]: return 0

         for i in range(1, len(s)):
             if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]:
                 return 1

         cut = [x for x in range(-1, len(s))]
         for i in range(len(s)):
             j=0
             while i - j >= 0 and i + j < len(s) and s[i - j] == s[i + j]:
                 if cut[i + j + 1]>cut[i - j] + 1:
                     cut[i + j + 1]=cut[i - j] + 1
                 j += 1
             j=0
             while i - j >= 0 and i + j + 1 < len(s) and s[i - j] == s[i + j + 1]:
                 if cut[i + j + 2]>cut[i - j] + 1:
                     cut[i + j + 2] = cut[i - j] + 1
                 j += 1
         return cut[-1]


Solve in Python:
Given a string s, return the last substring of s in lexicographical order.

Example 1:
Input: "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".

Example 2:
Input: "leetcode"
Output: "tcode"

Note:

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

class Solution:
    def lastSubstring(self, s: str) -> str:
        if not s: return None
        # get max char from s
        max_char = max(s)
        max_idxs = []
        # get all max_char indexs to append into max_idxs
        for i in range(len(s)):
            if s[i]==max_char:
                ## only store the first ind for consecutive max chars
                if not max_idxs or s[i-1]!=max_char:
                    max_idxs.append(i)
        # also append the length of s into the max_idxs for compersion
        max_idxs.append(len(s))
        #print(max_idxs)
        # initialize the temp max letter
        max_substring = s[max_idxs[0]:max_idxs[1]]
        ans_idx = max_idxs[0]

        # using for loop to compare with each short letter those leading by max_char
        for i in range(1, len(max_idxs)-1):
            cur = s[max_idxs[i]:max_idxs[i+1]]
            #print(cur)
            if max_substring==cur[:len(max_substring)]: #  like \"zazaa\" case
                max_substring = max_substring + cur
                ans_idx = max_idxs[i-1]
            elif max_substring<cur:
                max_substring = cur
                ans_idx = max_idxs[i]

        return s[ans_idx:]


Solve in Python:
Given a string s, return the maximum number of ocurrences of any substring under the following rules:

The number of unique characters in the substring must be less than or equal to maxLetters.
The substring size must be between minSize and maxSize inclusive.

Example 1:
Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output: 2
Explanation: Substring "aab" has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).

Example 2:
Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
Output: 2
Explanation: Substring "aaa" occur 2 times in the string. It can overlap.

Example 3:
Input: s = "aabcabcab", maxLetters = 2, minSize = 2, maxSize = 3
Output: 3

Example 4:
Input: s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3
Output: 0

Constraints:

1 <= s.length <= 10^5
1 <= maxLetters <= 26
1 <= minSize <= maxSize <= min(26, s.length)
s only contains lowercase English letters.

class Solution:
    def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
        def valid(sub):
            seen = set()
            for c in sub: seen.add(c)
            return len(seen)

        counts = dict()
        start = 0
        while start < len(s):
            end = start+minSize
            while end <= len(s) and end <= start + maxSize:
                sub = s[start:end]
                if sub in counts:
                    counts[sub] += 1
                else:
                    num_letters = valid(sub)
                    if num_letters <= maxLetters:
                        counts[sub] = 1
                    else:
                        break
                end += 1
            start += 1

        l = list(counts.values())
        if len(l) == 0: return 0
        return max(l)


Solve in Python:
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.

Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.

Example 2:
Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.

Example 3:
Input: s = "triplepillooooow"
Output: 5

Example 4:
Input: s = "hooraaaaaaaaaaay"
Output: 11

Example 5:
Input: s = "tourist"
Output: 1

Constraints:

1 <= s.length <= 500
s contains only lowercase English letters.

class Solution:
    def maxPower(self, s: str) -> int:

        count = 0
        new_count = 0
        for i,char in enumerate(s):

            print(char)
            try:
                if s[i+1] == char:
                    new_count += 1
                else:
                    print('afwww')
                    if new_count >= count:
                        count = new_count
                    new_count = 0
            except:
                print('sefesf')
                if new_count >= count:
                    print('sfwafawfawfawfawfawf')
                    count = new_count
                    new_count = 0
                break

        return count+1


Solve in Python:
Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not.

Valid examples, should return true:

should return false:

def isDigit(string: str) -> bool:
    """ Check if given string is a valid number. """
    try:
        float(string.strip())
        return True
    except ValueError:
        return False


Solve in Python:
Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

Example 1:

Input: "aacecaaa"
Output: "aaacecaaa"

Example 2:

Input: "abcd"
Output: "dcbabcd"

class Solution:

     def shortestPalindrome(self, s):
         """
         :type s: str
         :rtype: str
         """
         r = s[::-1]
         for i in range(len(s)):
             if s.startswith(r[i:]):
                 return r[:i] + s
         return r + s


Solve in Python:
Given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it palindrome.
Return the length of the maximum length awesome substring of s.

Example 1:
Input: s = "3242415"
Output: 5
Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.

Example 2:
Input: s = "12345678"
Output: 1

Example 3:
Input: s = "213123"
Output: 6
Explanation: "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps.

Example 4:
Input: s = "00"
Output: 2

Constraints:

1 <= s.length <= 10^5
s consists only of digits.

class Solution:
    def longestAwesome(self, s: str) -> int:
        left_most_masks = {0:-1}
        valid_masks =  {1 << i for i in range(10)} | {0}
        ans = 0
        cur_mask = 0

        for idx, x in enumerate(list(s)):
            cur_mask = cur_mask ^ 1 << int(x)
            for valid_mask in valid_masks:
                left_mask = valid_mask ^ cur_mask
                if left_mask in left_most_masks:
                    ans = max(ans, idx - left_most_masks[left_mask])
            if cur_mask not in left_most_masks:
                left_most_masks[cur_mask] = idx
        return ans


Solve in Python:
Given a string s. Can you make it a palindrome by deleting exactly one character? Note that size of the string after deletion would be one less than it was before.

-----Input-----
First line of the input contains a single integer T denoting number of test cases.
For each test case, you are given a single line containing string  s.

-----Output-----
For each test case, print YES or NO depending on the answer of the problem.

-----Constraints-----
Subtask 1, 35 points
-  1 ≤ T ≤ 100
- 2 ≤  size of string s ≤ 1000
-  String s contains lowercase English alphabets (ie. from 'a' to 'z').

Subtask 2, 65 points
- 2 ≤  size of string s ≤ 10^5
-  Sum of size of string s over all the input test cases won't exceed 10^6
-  String s contains lowercase English alphabets (ie. from 'a' to 'z').

-----Example-----
Input:
4
aaa
abc
abdbca
abba

Output:
YES
NO
YES
YES

-----Explanation-----
Example case 1. Delete any one 'a', resulting string is "aa" which is a palindrome.
Example case 2. It is not possible to delete exactly one character and having a palindrome.
Example case 3. Delete 'c', resulting string is "abdba" which is a palindrome.
Example case 4. Delete 'b', resulting string is "aba" which is a palindrome.

from collections import Counter
for _ in range(int(input())):
 data = input()
 each_char_count = Counter(data)
 count_ = 0
 status = False
 for i in each_char_count:
  if each_char_count[i]%2!=0:
   count_ += 1
  if count_ > 2:
   status = True
   break
 if status == False:
  print("YES")
 else:
  print("NO")


Solve in Python:
Given a string s. You should re-order the string using the following algorithm:

Pick the smallest character from s and append it to the result.
Pick the smallest character from s which is greater than the last appended character to the result and append it.
Repeat step 2 until you cannot pick more characters.
Pick the largest character from s and append it to the result.
Pick the largest character from s which is smaller than the last appended character to the result and append it.
Repeat step 5 until you cannot pick more characters.
Repeat the steps from 1 to 6 until you pick all characters from s.

In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.
Return the result string after sorting s with this algorithm.

Example 1:
Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"

Example 2:
Input: s = "rat"
Output: "art"
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.

Example 3:
Input: s = "leetcode"
Output: "cdelotee"

Example 4:
Input: s = "ggggggg"
Output: "ggggggg"

Example 5:
Input: s = "spo"
Output: "ops"

Constraints:

1 <= s.length <= 500
s contains only lower-case English letters.

class Solution:
    def sortString(self, s: str) -> str:
        from collections import Counter
        counts = Counter(s)
        characters = sorted(set(s))
        ch_len = len(characters)
        total = 0
        res = ''
        while total < len(s):
            for i in range(ch_len):
                ch = characters[i]
                if counts[ch] > 0:
                    res += ch
                    total += 1
                    counts[ch] -= 1
            for i in range(ch_len)[::-1]:
                ch = characters[i]
                if counts[ch] > 0:
                    res += ch
                    total += 1
                    counts[ch] -= 1
        return res


Solve in Python:
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.

Below is one possible representation of s1 = "great":

    great
   /    \
  gr    eat
 / \    /  \
g   r  e   at
           / \
          a   t

To scramble the string, we may choose any non-leaf node and swap its two children.

For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".

    rgeat
   /    \
  rg    eat
 / \    /  \
r   g  e   at
           / \
          a   t

We say that "rgeat" is a scrambled string of "great".

Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".

    rgtae
   /    \
  rg    tae
 / \    /  \
r   g  ta  e
       / \
      t   a

We say that "rgtae" is a scrambled string of "great".

Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.

Example 1:

Input: s1 = "great", s2 = "rgeat"
Output: true

Example 2:

Input: s1 = "abcde", s2 = "caebd"
Output: false

class Solution:

     def __init__(self):
         self._cache = {}

     def isScramble(self, A, B):

         if (A, B) in self._cache:
             return self._cache[(A, B)]

         if len(A) != len(B) or sorted(A) != sorted(B):
             self._cache[(A, B)] = False
             return False

         if len(A) == 1 or A == B:
             self._cache[(A, B)] = True
             return True

         for i in range(1, len(A)):
             if self.isScramble(A[:i], B[:i]) and self.isScramble(A[i:], B[i:]):
                 self._cache[(A, B)] = True
                 return True
             elif self.isScramble(A[:i], B[-i:]) and self.isScramble(A[i:], B[:-i]):
                 self._cache[(A, B)] = True
                 return True
         self._cache[(A, B)] = False
         return False


Solve in Python:
Given a string s of '(' , ')' and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:

It is the empty string, contains only lowercase characters, or
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.

Example 1:
Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.

Example 2:
Input: s = "a)b(c)d"
Output: "ab(c)d"

Example 3:
Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.

Example 4:
Input: s = "(a(b(c)d)"
Output: "a(b(c)d)"

Constraints:

1 <= s.length <= 10^5
s[i] is one of  '(' , ')' and lowercase English letters.

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        l, stack= 0, []
        for i in s:
            if i not in ('()'):
                stack.append(i)
            elif i == '(':
                l += 1
                stack.append('(')
            else:
                if l == 0:
                    continue
                else:
                    stack.append(')')
                    l -= 1
        i = len(stack) - 1
        while l > 0 and i >=0:
            if stack[i] == '(':
                stack[i] = ''
                l -= 1
            i -= 1
        return ''.join(stack)


Solve in Python:
Given a string text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters.

Example 1:
Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa", which its length is 3.

Example 2:
Input: text = "aaabaaa"
Output: 6
Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa", which its length is 6.

Example 3:
Input: text = "aaabbaaa"
Output: 4

Example 4:
Input: text = "aaaaa"
Output: 5
Explanation: No need to swap, longest repeated character substring is "aaaaa", length is 5.

Example 5:
Input: text = "abcdef"
Output: 1

Constraints:

1 <= text.length <= 20000
text consist of lowercase English characters only.

class Solution:
    def maxRepOpt1(self, text: str) -> int:
        letters = {}
        for i, char in enumerate(text):
            if char in letters:
                letters[char].append(i)
            else:
                letters[char] = [i]

        if len(letters) == 1:
            return len(text)

        ans = 0
        for letter in letters:
            cur = 0
            prev = 0
            discarded = False
            maxSoFar = 0
            arr = letters[letter]
            for j, pos in enumerate(arr):
                if not j:
                    cur = 1
                elif pos - arr[j-1] == 1:
                    cur += 1
                else:
                    if not discarded and prev:
                        discarded = True
                    elif not discarded and pos - arr[j-1] > 2:
                        discarded = True

                    if prev + cur > maxSoFar:
                        maxSoFar = prev+cur

                    if pos - arr[j-1] == 2:
                        prev = cur
                        cur = 1
                    else:
                        prev = 0
                        cur = 1
            print((prev+cur))
            if prev + cur > maxSoFar:
                    maxSoFar = prev+cur
            if discarded:
                maxSoFar+=1
            if maxSoFar > ans:
                ans = maxSoFar

        return ans


Solve in Python:
Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.

Note:
Both the string's length and k will not exceed 104.

Example 1:

Input:
s = "ABAB", k = 2

Output:
4

Explanation:
Replace the two 'A's with two 'B's or vice versa.

Example 2:

Input:
s = "AABABBA", k = 1

Output:
4

Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.

class Solution:
     def characterReplacement(self, s, k):
         """
         :type s: str
         :type k: int
         :rtype: int
         """
         ls = len(s)
         start, end, max_len = 0, 0, 0
         char_map, cnt, cur_max_char = {}, 0, 0
         while end < ls:
             # print(char_map)
             if s[end] in char_map:
                 char_map[s[end]] += 1
             else:
                 char_map[s[end]] = 1
             cnt += 1
             if char_map[s[end]] > cur_max_char:
                 cur_max_char = char_map[s[end]]
             # invalid
             if cnt - cur_max_char > k:
                 char_map[s[start]] -= 1
                 start += 1
                 cnt -= 1
             else:
                 max_len = max(max_len, cnt)
             end += 1

         return max_len


Solve in Python:
Given a string that includes alphanumeric characters ('3a4B2d') return the expansion of that string: The numeric values represent the occurrence of each letter preceding that numeric value. There should be no numeric characters in the final string. Empty strings should return an empty string.

The first occurrence of a numeric value should be the number of times each character behind it is repeated, until the next numeric value appears.
```python
string_expansion('3D2a5d2f') == 'DDDaadddddff'
```
```python
string_expansion('3abc') == 'aaabbbccc'       # correct
string_expansion('3abc') != 'aaabc'           # wrong
string_expansion('3abc') != 'abcabcabc'       # wrong
```
If there are two consecutive numeric characters the first one is ignored.

```python
string_expansion('3d332f2a') == 'dddffaa'
```
If there are two consecutive alphabetic characters then the first character has no effect on the one after it.

```python
string_expansion('abcde') == 'abcde'
```
Your code should be able to work for both lower and capital case letters.

```python
string_expansion('') == ''
```

def string_expansion(s):
    from re import findall
    result = findall('^[a-zA-Z]*', s)[0]
    for i in findall('(\d)([a-zA-Z]+)', s):
        for j in i[1]:
            result += j*int(i[0])
    return result


Solve in Python:
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

class Solution:
     def longestPalindrome(self, s):

         l = list(s)
         result = 0

         for x in set(s):
             x_count = l.count(x)
             if x_count % 2 == 0:
                 result += x_count
             else:
                 result += x_count-1

         if len(l) > result:
             result += 1

         return result


Solve in Python:
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example 1:

Input: "bcabc"
Output: "abc"

Example 2:

Input: "cbacdcbc"
Output: "acdb"

class Solution:
     def removeDuplicateLetters(self, s):
         if not s:
             return ""

         res = ''
         sorted_set = sorted(set(s))

         for c in sorted_set:
             sub_s = s[s.index(c):]
             if set(s) == set(sub_s):
                 return c + self.removeDuplicateLetters(sub_s.replace(c, ''))

         return res


Solve in Python:
Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `0` will be considered even.

For example, `capitalize("abcdef") = ['AbCdEf', 'aBcDeF']`. See test cases for more examples.

The input will be a lowercase string with no spaces.

Good luck!

If you like this Kata, please try:

[Indexed capitalization](https://www.codewars.com/kata/59cfc09a86a6fdf6df0000f1)

[Even-odd disparity](https://www.codewars.com/kata/59c62f1bdcc40560a2000060)

def capitalize(s):
    final1 = ""
    final2 = ""

    for x in range(len(s)):  #1st string
        final1 += s[x].upper() if x%2==0 else s[x]

    for x in final1: #toggle 1st string to get the 2ns string
        final2 += x.lower() if x.isupper() else x.upper()

    return [final1,final2]


Solve in Python:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

class Solution:
     def isPalindrome(self, s):
         """
         :type s: str
         :rtype: bool
         """
         cleanlist = [c for c in s.lower() if c.isalnum()]
         return cleanlist == cleanlist[::-1]


Solve in Python:
Given a string, determine if it's a valid identifier.

## Here is the syntax for valid identifiers:
* Each identifier must have at least one character.
* The first character must be picked from: alpha, underscore, or dollar sign. The first character cannot be a digit.
* The rest of the characters (besides the first) can be from: alpha, digit, underscore, or dollar sign. In other words, it can be any valid identifier character.

### Examples of valid identifiers:
* i
* wo_rd
* b2h

### Examples of invalid identifiers:
* 1i
* wo rd
* !b2h

import re

def is_valid(idn):
    # Your code here
    line = re.match(r'[a-zA-Z_$]\w*$', idn)
    if line:
        return True
    else:
        return False


Solve in Python:
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

class Solution:
     def firstUniqChar(self, s):
         """
         :type s: str
         :rtype: int
         """

         letters='abcdefghijklmnopqrstuvwxyz'

         list = [ l for l in letters if s.count(l) == 1]

         for i in range(0, len(s)):
             if s[i] in list:
                 return i

         return -1


Solve in Python:
Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

class Solution:
     def lengthOfLongestSubstring(self, s):
         """
         :type s: str
         :rtype: int
         """
         result = 0
         if len(s) == 0:
             return result

         hashmap = {}
         start = 0
         for i in range(len(s)):
             if s[i] in hashmap:
                 start = max(hashmap[s[i]] + 1,start)
             hashmap[s[i]] = i
             result = max(result,i-start+1)
         return result


Solve in Python:
Given a string, remove any characters that are unique from the string.

Example:

input: "abccdefee"

output: "cceee"

def only_duplicates(string):
    sets = unique, duplicate = set(), set()
    for c in string: sets[c in unique].add(c)
    return ''.join(c for c in string if c in duplicate)


Solve in Python:
Given a string, return a new string that has transformed based on the input:

* Change case of every character, ie. lower case to upper case, upper case to lower case.
* Reverse the order of words from the input.

**Note:** You will have to handle multiple spaces, and leading/trailing spaces.

For example:

```
"Example Input" ==> "iNPUT eXAMPLE"
```

You may assume the input only contain English alphabet and spaces.

def string_transformer(s):
    s = s.split(" ")
    s = s[::-1]
    s = " ".join(s)
    result = ""

    for letter in s:
        if letter.islower():
            result = result + letter.upper()
        elif letter.isupper():
            result = result + letter.lower()
        else:
            result = result + letter

    return result


Solve in Python:
Given a string, return the minimal number of parenthesis reversals needed to make balanced parenthesis.

For example:
```Javascript
solve(")(") = 2 Because we need to reverse ")" to "(" and "(" to ")". These are 2 reversals.
solve("(((())") = 1 We need to reverse just one "(" parenthesis to make it balanced.
solve("(((") = -1 Not possible to form balanced parenthesis. Return -1.
```

Parenthesis will be either `"("` or `")"`.

More examples in the test cases.

Good luck.


Solve in Python:
Given a string, s, return a new string that orders the characters in order of frequency.

The returned string should have the same number of characters as the original string.

Make your transformation stable, meaning characters that compare equal should stay in their original order in the string s.

```python
most_common("Hello world") => "lllooHe wrd"
most_common("Hello He worldwrd") => "lllHeo He wordwrd"
```

Explanation:

In the `hello world` example, there are 3 `'l'`characters, 2 `'o'`characters, and one each of `'H'`, `'e'`, `' '`, `'w'`, `'r'`, and `'d'`characters. Since `'He wrd'`are all tied, they occur in the same relative order that they do in the original string, `'Hello world'`.

Note that ties don't just happen in the case of characters occuring once in a string. See the second example, `most_common("Hello He worldwrd")`should return `'lllHeo He wordwrd'`, not `'lllHHeeoo  wwrrdd'`.  **This is a key behavior if this method were to be used to transform a string on multiple passes.**

from collections import Counter
def most_common(s):
    c=Counter(s)
    return "".join(sorted(s,key=lambda x:-c[x]))


Solve in Python:
Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:

Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

class Solution:
     def frequencySort(self, s):
         """
         :type s: str
         :rtype: str
         """
         charToFreq = {}
         freqToChar = {}
         for c in s:
             if c not in charToFreq:
                 charToFreq[c] = 0
             charToFreq[c] += 1
         print(charToFreq)
         for key, value in list(charToFreq.items()):
             if value not in freqToChar:
                 freqToChar[value] = []
             freqToChar[value].append(key)
         print(freqToChar)
         result = []
         for key in sorted(freqToChar, reverse = True):
             for char in freqToChar[key]:
                 result += [char] * key
         return "".join(result)


Solve in Python:
Given a string, swap the case for each of the letters.

e.g. CodEwArs --> cODeWaRS

### Examples

```
""           ->   ""
"CodeWars"   ->   "cODEwARS"
"abc"        ->   "ABC"
"ABC"        ->   "abc"
"123235"     ->   "123235"
```


Solve in Python:
Given a string, turn each letter into its ASCII character code and join them together to create a number - let's call this number `total1`:

```
'ABC' --> 'A' = 65, 'B' = 66, 'C' = 67 --> 656667
```

Then replace any incidence of the number `7` with the number `1`, and call this number 'total2':
```
total1 = 656667
              ^
total2 = 656661
              ^
```

Then return the difference between the sum of the digits in `total1` and `total2`:

```
  (6 + 5 + 6 + 6 + 6 + 7)
- (6 + 5 + 6 + 6 + 6 + 1)
-------------------------
                       6
```

def calc(x):
    total1 = "".join(str(ord(char)) for char in x)
    total2 = total1.replace("7","1")
    return sum(int(x) for x in total1) - sum(int(x) for x in total2)


Solve in Python:
Given a string, you have to return a string in which each character (case-sensitive) is repeated once.

```python
double_char("String") ==> "SSttrriinngg"

double_char("Hello World") ==> "HHeelllloo  WWoorrlldd"

double_char("1234!_ ") ==> "11223344!!__  "
```
Good Luck!

def double_char(s):
    lst = list(s)
    res = ''
    for el in lst:
        res += el * 2
    return res


Solve in Python:
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note:
In the string, each word is separated by single space and there will not be any extra space in the string.

class Solution:
     def reverseWords(self, s):
         """
         :type s: str
         :rtype: str
         """
         words = s.split(" ")
         output = ""

         for i, word in enumerate(words):
             output += word[::-1]
             if i != len(words) - 1:
                 output += " "

         return output


Solve in Python:
Given a string, you progressively need to concatenate the first letter from the left and the first letter to the right and "1", then the second letter from the left and the second letter to the right and "2", and so on.

If the string's length is odd drop the central element.

For example:
```python
char_concat("abcdef")    == 'af1be2cd3'
char_concat("abc!def")   == 'af1be2cd3' # same result
```

def char_concat(word):
    m = (len(word) + 2) // 2
    return ''.join(a + b + str(i) for i, (a, b) in enumerate(zip(word[:m], word[-1:-m:-1]), 1))


Solve in Python:
Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note:

The input string length won't exceed 1000.

class Solution:
     def countSubstrings(self, s):
         """
         :type s: str
         :rtype: int
         """

         # manacher, find Z
         s = '^#' + '#'.join(s) + '#$'
         Z = [1] * len(s)
         center, right = 0, 0
         for i in range(len(s)-1): # 注意 i不能取到 $
             if i < right:
                 i_mirror = 2 * center - i
                 Z[i] = min(Z[i_mirror], right - i + 1)
             while s[i+Z[i]] == s[i-Z[i]]:
                 Z[i] += 1
             if i + Z[i] - 1 > right:
                 center, right = i, i + Z[i] - 1

         # sum Z
         return sum(z//2 for z in Z)


Solve in Python:
Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.
Formally, a parentheses string is valid if and only if:

It is the empty string, or
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.

Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

Example 1:
Input: "())"
Output: 1

Example 2:
Input: "((("
Output: 3

Example 3:
Input: "()"
Output: 0

Example 4:
Input: "()))(("
Output: 4

Note:

S.length <= 1000
S only consists of '(' and ')' characters.

class Solution:
    def minAddToMakeValid(self, S: str) -> int:
        if not S:
            return 0
        N = len(S)
        open_brackets = [0]*N
        close_brackets = [0]*N

        ans = 0
        for i, c in enumerate(S):
            if i>0:
                open_brackets[i] = open_brackets[i-1]
                close_brackets[i] = close_brackets[i-1]
            if c == '(':
                open_brackets[i] += 1
            elif c == ')':
                close_brackets[i] += 1

            if close_brackets[i] > open_brackets[i]:
                diff = close_brackets[i]-open_brackets[i]
                ans += diff
                open_brackets[i] += diff

        return ans+open_brackets[-1]-close_brackets[-1]