Solve in Python:
Given an array of integers `a` and integers `t` and `x`, count how many elements in the array you can make equal to `t` by **increasing** / **decreasing** it by `x` (or doing nothing).
*EASY!*

```python
# ex 1

a = [11, 5, 3]
t = 7
x = 2

count(a, t, x) # => 3
```
- you can make 11 equal to 7 by subtracting 2 twice
- you can make 5 equal to 7 by adding 2
- you can make 3 equal to 7 by adding 2 twice

```python
# ex 2

a = [-4,6,8]
t = -7
x = -3

count(a, t, x) # => 2
```

## Constraints
**-10^(18) <= a[i],t,x <= 10^(18)**

**3 <= |a| <= 10^(4)**

def count(a, t, y):
  return sum(not (x-t) % y if y else x == t for x in a)


Solve in Python:
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

class Solution:
     def containsNearbyDuplicate(self, nums, k):
         """
         :type nums: List[int]
         :type k: int
         :rtype: bool
         """
         s = set()
         for i in range(len(nums)):
             if i-k-1 >= 0:
                 s.remove(nums[i-k-1])

             if nums[i] in s:
                 return True
             s.add(nums[i])
         return False


Solve in Python:
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example 1:

Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).Although we have two 1s in the input, we should only return the number of unique pairs.

Example 2:

Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

Example 3:

Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

Note:

The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].

class Solution:
     def findPairs(self, nums, k):
         """
         :type nums: List[int]
         :type k: int
         :rtype: int
         """

         ### 2 pointers
         # result = 0;
         # nums.sort()
         # for i in range(len(nums) - 1):
         #     if i == 0 or (i != 0 and nums[i] != nums[i - 1]):
         #         for j in range(i + 1, len(nums)):
         #             if nums[j] - nums[i] == k:
         #                 result += 1
         #                 break
         #             elif nums[j] - nums[i] > k:
         #                 break
         # return result

         ### map
         result = 0
         c = collections.Counter(nums)
         for i in c:
             if k > 0 and i + k in c or k == 0 and c[i] > 1:
                 result += 1
         return result


Solve in Python:
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2

Note:

The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

class Solution:
     def subarraySum(self, nums, k):
         """
         :type nums: List[int]
         :type k: int
         :rtype: int
         """
         cum_sum_dict = {}
         cum_sum_dict[0] = 1
         left_sum = 0
         count = 0
         for t in nums:
             left_sum = left_sum + t
             if (left_sum - k) in cum_sum_dict:
                 count = count + cum_sum_dict[left_sum - k]
             if left_sum in cum_sum_dict:
                 cum_sum_dict[left_sum] = cum_sum_dict[left_sum] + 1
             else:
                 cum_sum_dict[left_sum] = 1

         return count


Solve in Python:
Given an array of integers arr and an integer target.
You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.

Example 1:
Input: arr = [3,2,2,4,3], target = 3
Output: 2
Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.

Example 2:
Input: arr = [7,3,4,7], target = 7
Output: 2
Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.

Example 3:
Input: arr = [4,3,2,6,2,3,4], target = 6
Output: -1
Explanation: We have only one sub-array of sum = 6.

Example 4:
Input: arr = [5,5,4,4,5], target = 3
Output: -1
Explanation: We cannot find a sub-array of sum = 3.

Example 5:
Input: arr = [3,1,1,1,5,1,2,1], target = 3
Output: 3
Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.

Constraints:

1 <= arr.length <= 10^5
1 <= arr[i] <= 1000
1 <= target <= 10^8

class Solution:
  # 872 ms
  def minSumOfLengths(self, arr, target):
    result = inf = 2**31-1
    i = window = 0
    premin = [inf] * len(arr)

    # i: window start, j: window end
    for j, num in enumerate(arr):
      window += num
      while window > target:
        window -= arr[i]
        i += 1
      if window == target:
        # curr: length
        curr = j - i + 1
        if result > curr + premin[i - 1]:
            result = curr + premin[i - 1]
        premin[j] = curr if curr < premin[j - 1] else premin[j - 1]

      else:
        premin[j] = premin[j - 1]

    return result if result < inf else -1


Solve in Python:
Given an array of integers arr and two integers k and threshold.
Return the number of sub-arrays of size k and average greater than or equal to threshold.

Example 1:
Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output: 3
Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).

Example 2:
Input: arr = [1,1,1,1,1], k = 1, threshold = 0
Output: 5

Example 3:
Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
Output: 6
Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.

Example 4:
Input: arr = [7,7,7,7,7,7,7], k = 7, threshold = 7
Output: 1

Example 5:
Input: arr = [4,4,4,4], k = 4, threshold = 1
Output: 1

Constraints:

1 <= arr.length <= 10^5
1 <= arr[i] <= 10^4
1 <= k <= arr.length
0 <= threshold <= 10^4

class Solution:
    def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:

        size = len(arr)

        avg = sum(arr[:k]) / k
        count = 1 if avg >= threshold else 0

        end = k

        while end < size:
            prevVal = arr[end-k] / k
            nextVal = arr[end] / k

            avg += nextVal - prevVal

            count += 1 if avg >= threshold else 0
            end += 1

        return count


Solve in Python:
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.

Example 1:
Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).

Example 2:
Input: arr = [1,2,3,4,5,6], k = 7
Output: true
Explanation: Pairs are (1,6),(2,5) and(3,4).

Example 3:
Input: arr = [1,2,3,4,5,6], k = 10
Output: false
Explanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.

Example 4:
Input: arr = [-10,10], k = 2
Output: true

Example 5:
Input: arr = [-1,1,-2,2,-3,3,-4,4], k = 3
Output: true

Constraints:

arr.length == n
1 <= n <= 10^5
n is even.
-10^9 <= arr[i] <= 10^9
1 <= k <= 10^5

class Solution:
    def canArrange(self, arr: List[int], k: int) -> bool:
        bag = {}
        for i in arr:
            if i < 0:
                i += ((-i) // k +1) * k

            r = i % k

            if r != 0:
                if k-r not in bag:
                    if r not in bag:
                        bag[r] = 0
                    bag[r] += 1
                else:
                    bag[k-r] -= 1
                    if bag[k-r] == 0:
                        del bag[k-r]
            else:
                if 0 in bag:
                    del bag[0]
                else:
                    bag[0]= 1
        return len(bag) == 0


Solve in Python:
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.

Example 1:
Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.

Example 2:
Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.

Example 3:
Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.

Example 4:
Input: arr = [5]
Output: -1

Example 5:
Input: arr = [7,7,7,7,7,7,7]
Output: 7

Constraints:

1 <= arr.length <= 500
1 <= arr[i] <= 500

class Solution:
    def findLucky(self, arr: List[int]) -> int:
        ans = -1
        for i in sorted(set(arr)):
            if i == arr.count(i):
                ans = i
        return ans


Solve in Python:
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:

0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c

Where |x| denotes the absolute value of x.
Return the number of good triplets.

Example 1:
Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
Output: 4
Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].

Example 2:
Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1
Output: 0
Explanation: No triplet satisfies all conditions.

Constraints:

3 <= arr.length <= 100
0 <= arr[i] <= 1000
0 <= a, b, c <= 1000

from itertools import combinations
class Solution:
    def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
        ans = [1 for i,j,k in combinations(arr,3) if abs(i-j)<=a and abs(j-k)<=b and abs(i-k)<=c]
        return sum(ans)


Solve in Python:
Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.

Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example 2:
Input: arr = [1,2]
Output: false

Example 3:
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true

Constraints:

1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000

class Solution:
    def uniqueOccurrences(self, arr: List[int]) -> bool:
        count = Counter(arr)
        s = set()

        for k,v in list(count.items()):
            if v in s:
                return False
            else:
                s.add(v)
        return True


Solve in Python:
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.

Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Odd sums are [1,9,3,5] so the answer is 4.

Example 2:
Input: arr = [2,4,6]
Output: 0
Explanation: All sub-arrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]
All sub-arrays sum are [2,6,12,4,10,6].
All sub-arrays have even sum and the answer is 0.

Example 3:
Input: arr = [1,2,3,4,5,6,7]
Output: 16

Example 4:
Input: arr = [100,100,99,99]
Output: 4

Example 5:
Input: arr = [7]
Output: 1

Constraints:

1 <= arr.length <= 10^5
1 <= arr[i] <= 100

class Solution:
    def numOfSubarrays(self, arr: List[int]) -> int:
        s, d, ans = 0, 0, 0
        for n in arr:
                if n%2:
                    s, d = d, s
                    s += 1
                else:
                    d += 1
                ans += s
                #print(n, ans)
        return ans%1000000007


Solve in Python:
Given an array of integers arr and an integer k.
A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.
If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].
Return a list of the strongest k values in the array. return the answer in any arbitrary order.
Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed).

For arr = [6, -3, 7, 2, 11], n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6.
For arr = [-7, 22, 17, 3], n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3.

Example 1:
Input: arr = [1,2,3,4,5], k = 2
Output: [5,1]
Explanation: Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.
Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.

Example 2:
Input: arr = [1,1,3,5,5], k = 2
Output: [5,5]
Explanation: Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].

Example 3:
Input: arr = [6,7,11,7,6,8], k = 5
Output: [11,8,6,6,7]
Explanation: Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].
Any permutation of [11,8,6,6,7] is accepted.

Example 4:
Input: arr = [6,-3,7,2,11], k = 3
Output: [-3,11,2]

Example 5:
Input: arr = [-7,22,17,3], k = 2
Output: [22,17]

Constraints:

1 <= arr.length <= 10^5
-10^5 <= arr[i] <= 10^5
1 <= k <= arr.length

class Solution:
    def getStrongest(self, arr: List[int], k: int) -> List[int]:
        median = sorted(arr)[(len(arr) - 1) // 2]
        return heapq.nsmallest(k, arr, key=lambda x: (-abs(x-median), -x))


Solve in Python:
Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers.

Return your answer as a number.

def sum_mix(arr):
    ans = []
    for i in arr:
        ans.append(int(i))
    return sum(ans)


Solve in Python:
Given an array of integers cost and an integer target. Return the maximum integer you can paint under the following rules:

The cost of painting a digit (i+1) is given by cost[i] (0 indexed).
The total cost used must be equal to target.
Integer does not have digits 0.

Since the answer may be too large, return it as string.
If there is no way to paint any integer given the condition, return "0".

Example 1:
Input: cost = [4,3,2,5,6,7,2,5,5], target = 9
Output: "7772"
Explanation:  The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2*3+ 3*1 = 9. You could also paint "977", but "7772" is the largest number.
Digit    cost
  1  ->   4
  2  ->   3
  3  ->   2
  4  ->   5
  5  ->   6
  6  ->   7
  7  ->   2
  8  ->   5
  9  ->   5

Example 2:
Input: cost = [7,6,5,5,5,6,8,7,8], target = 12
Output: "85"
Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12.

Example 3:
Input: cost = [2,4,6,2,4,6,4,4,4], target = 5
Output: "0"
Explanation: It's not possible to paint any integer with total cost equal to target.

Example 4:
Input: cost = [6,10,15,40,40,40,40,40,40], target = 47
Output: "32211"

Constraints:

cost.length == 9
1 <= cost[i] <= 5000
1 <= target <= 5000

class Solution:
    def largestNumber(self, cost: List[int], target: int) -> str:
        dp = [0] + [-1] * (target)
        for t in range(1, target + 1):
            for i, c in enumerate(cost):
                if t - c >= 0:
                    dp[t] = max(dp[t], dp[t - c] * 10 + i + 1)
        return str(max(dp[target], 0))


Solve in Python:
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal.

Example 1:

Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.

Note:
1 .
0 < nums[i] < 10000.

class Solution:
     def canPartitionKSubsets(self, nums, k):
         """
         :type nums: List[int]
         :type k: int
         :rtype: bool
         """
         total = sum(nums)
         if total % k != 0:
             return False
         subsetTotal = total // k
         visited = [0] * len(nums)
         return self.helper(k, 0, 0, visited, nums, k, subsetTotal)

     def helper(self, remainingSets, index, s, visited, nums, k, subsetTotal):
         if remainingSets == 1:
             return True
         if s == subsetTotal:
             return self.helper(remainingSets - 1, 0, 0, visited, nums, k, subsetTotal)
         for i in range(index, len(nums)):
             if visited[i] == 0 and s + nums[i] <= subsetTotal:
                 visited[i] = 1
                 if self.helper(remainingSets, i + 1, s + nums[i], visited, nums, k, subsetTotal):
                     return True
                 visited[i] = 0
         return False


Solve in Python:
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.

Example 1:
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].

Example 2:
Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There is no odd numbers in the array.

Example 3:
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16

Constraints:

1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length

# 20201007 ref
class Solution:
    def numberOfSubarrays(self, A: List[int], k: int) -> int:
        d = []
        n = len(A)
        res = 0
        count = 1
        for i in range(n):
            if (A[i] % 2):
                d.append(count)
                count = 1
            else:
                count += 1
        d.append(count)
        for x,y in zip(d,d[k:]):
            res += x * y
        return res


Solve in Python:
Given an array of integers nums and an integer target.
Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal than target.
Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:
Input: nums = [3,5,6,7], target = 9
Output: 4
Explanation: There are 4 subsequences that satisfy the condition.
[3] -> Min value + max value <= target (3 + 3 <= 9)
[3,5] -> (3 + 5 <= 9)
[3,5,6] -> (3 + 6 <= 9)
[3,6] -> (3 + 6 <= 9)

Example 2:
Input: nums = [3,3,6,8], target = 10
Output: 6
Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
Example 3:
Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
Explanation: There are 63 non-empty subsequences, two of them don't satisfy the condition ([6,7], [7]).
Number of valid subsequences (63 - 2 = 61).

Example 4:
Input: nums = [5,2,4,1,7,6,8], target = 16
Output: 127
Explanation: All non-empty subset satisfy the condition (2^7 - 1) = 127

Constraints:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
1 <= target <= 10^6

class Solution:
    def numSubseq(self, nums: List[int], target: int) -> int:
        if not nums:
            return 0
        res = 0
        nums.sort()
        ln = len(nums)
        i = 0
        j = ln-1
        md = pow(10,9)+7

        while i <= j:
            if nums[i]+nums[j]<= target:
                res = (res + pow(2, j-i, md))%md
                i += 1
            else:
                j -= 1
        return res


Solve in Python:
Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.

Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).

Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3

Example 3:
Input: nums = [19], threshold = 5
Output: 4

Constraints:

1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6

class Solution:
    def smallestDivisor(self, nums: List[int], threshold: int) -> int:
        def check(div):
            # print(sum([elem/div if elem % div == 0 else (elem//div)+1 for elem in nums]))
            return threshold >= sum([elem/div if elem % div == 0 else (elem//div)+1 for elem in nums])

        def bst(low,high):
            # print(low,high)
            mid = (low+high) // 2
            if low > high:
                return -1
            elif low == high:
                if check(low):
                    return low
                else:
                    return -1
            else:
                if check(mid):
                    ambition = bst(low,mid-1)
                    if ambition != -1:
                        return ambition
                    else:
                        return mid
                else:
                    return bst(mid+1,high)

        return bst(1,10**9)


Solve in Python:
Given an array of integers nums, sort the array in ascending order.

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

Constraints:

1 <= nums.length <= 50000
-50000 <= nums[i] <= 50000

class Solution:
    def sortArray(self, nums: List[int]) -> List[int]:
        if len(nums) <= 1:
            return nums
        mid = int(len(nums)/2)
        left = self.sortArray(nums[0:mid])
        right = self.sortArray(nums[mid:])
        return self.merge(left, right)
    def merge(self, left, right):
        i = j = 0
        ret = []
        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                ret.append(left[i])
                i += 1
            elif right[j] <= left[i]:
                ret.append(right[j])
                j += 1
        ret.extend(left[i:])
        ret.extend(right[j:])
        return ret


Solve in Python:
Given an array of integers nums, write a method that returns the "pivot" index of this array.

We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

Example 1:

Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.

Example 2:

Input:
nums = [1, 2, 3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.

Note:
The length of nums will be in the range [0, 10000].
Each element nums[i] will be an integer in the range [-1000, 1000].

class Solution:
     def pivotIndex(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         l = len(nums)
         if l < 3:
             return -1

         s = [0] * l
         s[0] = nums[0]
         for i in range(1, l):
             s[i] = s[i-1]+ nums[i]

         d=[0]* l
         d[l-1] = nums[l-1]
         for j in range(l-2,-1,-1):
             d[j] = d[j+1] + nums[j]

         for i in range(0, l):
             if(s[i] == d[i]):
                 return i

         return -1


Solve in Python:
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.

Example:

int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);

// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);

// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);

class Solution:

     def __init__(self, nums):
         """
         :type nums: List[int]
         """
         self.nums = nums;

     def pick(self, target):
         """
         :type target: int
         :rtype: int
         """
         indices = [i for i, x in enumerate(self.nums) if x == target]
         return random.choice(indices)

 # Your Solution object will be instantiated and called as such:
 # obj = Solution(nums)
 # param_1 = obj.pick(target)


Solve in Python:
Given an array of integers your solution should find the smallest integer.

For example:

- Given `[34, 15, 88, 2]` your solution will return `2`
- Given `[34, -345, -1, 100]` your solution will return `-345`

You can assume, for the purpose of this kata, that the supplied array will not be empty.

def find_smallest_int(arr):
    anwser = 9999999
    for a in arr:
        if a < anwser:
            anwser = a
    return anwser


Solve in Python:
Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

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

Example 2:

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

Example 3:

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

class Solution:
     def containsDuplicate(self, nums):
         """
         :type nums: List[int]
         :rtype: bool
         """
         nums.sort()

         if len(nums)-1 == 1:
             if nums[0] == nums[1]:
                 return True

         for i in range(1,len(nums)):
             print(i)

             if nums[i] == nums[i-1]:
                 return True

         return False


Solve in Python:
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false

class Solution:
     def containsNearbyAlmostDuplicate(self, nums, k, t):
         """
         :type nums: List[int]
         :type k: int
         :type t: int
         :rtype: bool
         """
         if len(nums) < 2 or k <= 0 or t < 0: return False
         if t == 0:
             visited = set()
             for i, n in enumerate(nums):
                 if n in visited: return True
                 visited.add(n)
                 if i >= k: visited.remove(nums[i-k])
             return False
         bucket = {}
         for i, n in enumerate(nums):
             b = n // t
             if b in bucket: return True
             if b+1 in bucket and abs(bucket[b+1]-n) <= t: return True
             if b-1 in bucket and abs(bucket[b-1]-n) <= t: return True
             bucket[b] = n
             if i >= k: del bucket[nums[i-k]//t]
         return False


Solve in Python:
Given an array of integers, find the one that appears an odd number of times.

There will always be only one integer that appears an odd number of times.

def find_it(seq):
    for i in seq:
        if seq.count(i)%2!=0:
            return i


Solve in Python:
Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be non-empty after deleting one element.

Example 1:
Input: arr = [1,-2,0,3]
Output: 4
Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.
Example 2:
Input: arr = [1,-2,-2,3]
Output: 3
Explanation: We just choose [3] and it's the maximum sum.

Example 3:
Input: arr = [-1,-1,-1,-1]
Output: -1
Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.

Constraints:

1 <= arr.length <= 10^5
-10^4 <= arr[i] <= 10^4

class Solution:
    def maximumSum(self, arr: List[int]) -> int:
        if len(arr)==1:
            return arr[0]
        dp=[[0]*2 for i in range(len(arr))]
        dp[0][0]=arr[0]
        for i in range(1,len(arr)):
            dp[i][0]=max(arr[i],dp[i-1][0]+arr[i])
            dp[i][1]=max(dp[i-1][1]+arr[i],dp[i-1][0])
        ans=float('-inf')
        for i in range(len(arr)):
            ans=max(ans,dp[i][0],dp[i][1])
        if ans==0:
            return max(arr)
        return ans


Solve in Python:
Given an array of integers, return the smallest common factors of all integers in the array.

When i say **Smallest Common Factor** i mean the smallest number above 1 that can divide all numbers in the array without a remainder.

If there are no common factors above 1, return 1 (technically 1 is always a common factor).

def scf (arr):
    print(arr)
    if arr == []:
        return 1
    ret = []
    for j in arr:
        for i in range(1, int(j**0.5)+1):
            if j%i == 0:
                ret.append(i)
                ret.append(j//i)
    if len(ret) == len(arr)*2:
        return 1
    print(ret)
    ret1 = []
    for k in set(ret):
        if ret.count(k) >= len(arr) and k != 1:
            ret1.append(k)
    if ret1 == []:
        return 1
    else:
        return min(ret1)


Solve in Python:
Given an array of integers.

Return an array, where the first element is the count of positives numbers and the second element is sum of negative numbers.

If the input array is empty or null, return an empty array.

# Example

For input `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]`, you should return `[10, -65]`.

def count_positives_sum_negatives(arr):
    count,sumnegative=0,0
    for e in arr:
        if e>0:count+=1
        else:sumnegative+=e
    return []if arr==[] else [count,sumnegative]


Solve in Python:
Given an array of integers arr, sort the array by performing a series of pancake flips.
In one pancake flip we do the following steps:

Choose an integer k where 1 <= k <= arr.length.
Reverse the sub-array arr[1...k].

For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.
Return the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.

Example 1:
Input: arr = [3,2,4,1]
Output: [4,2,4,3]
Explanation:
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = [3, 2, 4, 1]
After 1st flip (k = 4): arr = [1, 4, 2, 3]
After 2nd flip (k = 2): arr = [4, 1, 2, 3]
After 3rd flip (k = 4): arr = [3, 2, 1, 4]
After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.
Notice that we return an array of the chosen k values of the pancake flips.

Example 2:
Input: arr = [1,2,3]
Output: []
Explanation: The input is already sorted, so there is no need to flip anything.
Note that other answers, such as [3, 3], would also be accepted.

Constraints:

1 <= arr.length <= 100
1 <= arr[i] <= arr.length
All integers in arr are unique (i.e. arr is a permutation of the integers from 1 to arr.length).

class Solution:
    def pancakeSort(self, arr: List[int]) -> List[int]:
        res = []
        A = arr
        for x in range(len(A), 1, -1):
            i = A.index(x)
            res.extend([i+1, x])
            A = A[x-1:i:-1] + A[:i]

        return res


Solve in Python:
Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.

Example 1:
Input: arr = [5,5,4], k = 1
Output: 1
Explanation: Remove the single 4, only 5 is left.

Example 2:
Input: arr = [4,3,1,1,3,3,2], k = 3
Output: 2
Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.

Constraints:

1 <= arr.length <= 10^5
1 <= arr[i] <= 10^9
0 <= k <= arr.length

class Solution:
    def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
        buckets = [[] for _ in range(len(arr) + 1)]
        counter = collections.Counter(arr)
        for key, count in counter.items():
            buckets[count].append(key)
        for count in range(len(arr) + 1):
            if k == 0: break
            while buckets[count] and k >= count:
                del counter[buckets[count].pop()]
                k -= count
        return len(counter)


Solve in Python:
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.

Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.

Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].

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

Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4

Constraints:

1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9

class Solution:
    def getMaxLen(self, nums: List[int]) -> int:

        def helper(nums):
            result = 1 if nums[0] > 0 else 0

            positiveSoFar = 1 if nums[0] > 0 else 0
            negativeSoFar = 1 if nums[0] < 0 else 0

            for i in range(1, len(nums)):
                if nums[i] == 0:
                    positiveSoFar = 0
                    negativeSoFar = 0
                elif nums[i] > 0 :
                    positiveSoFar += 1
                    if negativeSoFar > 0:
                        negativeSoFar += 1

                elif nums[i] < 0:
                    if negativeSoFar > 0:
                        positiveSoFar = max(negativeSoFar, positiveSoFar) +1
                        negativeSoFar = 0
                    else:
                        negativeSoFar = positiveSoFar + 1
                        positiveSoFar = 0

                result = max(result, positiveSoFar)
            return result

        return max(helper(nums), helper(nums[::-1]))


Solve in Python:
Given an array of integers nums, you start with an initial positive value startValue.
In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).
Return the minimum positive value of startValue such that the step by step sum is never less than 1.

Example 1:
Input: nums = [-3,2,-3,4,2]
Output: 5
Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
                step by step sum
                startValue = 4 | startValue = 5 | nums
                  (4 -3 ) = 1  | (5 -3 ) = 2    |  -3
                  (1 +2 ) = 3  | (2 +2 ) = 4    |   2
                  (3 -3 ) = 0  | (4 -3 ) = 1    |  -3
                  (0 +4 ) = 4  | (1 +4 ) = 5    |   4
                  (4 +2 ) = 6  | (5 +2 ) = 7    |   2

Example 2:
Input: nums = [1,2]
Output: 1
Explanation: Minimum start value should be positive.

Example 3:
Input: nums = [1,-2,-3]
Output: 5

Constraints:

1 <= nums.length <= 100
-100 <= nums[i] <= 100

class Solution:
    def minStartValue(self, nums: List[int]) -> int:
        n = len(nums)

        startValue = 1

        while startValue < float('inf'):
            get = True
            tmp = startValue
            for i in range(n):
                if nums[i] + tmp < 1:
                    get = False
                    break
                tmp = nums[i] + tmp
            if not get:
                startValue += 1
            else:
                return startValue


Solve in Python:
Given an array of integers nums.
A pair (i,j) is called good if nums[i] == nums[j] and i < j.
Return the number of good pairs.

Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.

Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.

Example 3:
Input: nums = [1,2,3]
Output: 0

Constraints:

1 <= nums.length <= 100
1 <= nums[i] <= 100

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        counter = collections.Counter(nums)
        answer = 0

        for k, v in counter.items():
            answer += v * (v - 1) // 2
        return answer


Solve in Python:
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into sets of k consecutive numbers
Return True if its possible otherwise return False.

Example 1:
Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].

Example 2:
Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: true
Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].

Example 3:
Input: nums = [3,3,2,2,1,1], k = 3
Output: true

Example 4:
Input: nums = [1,2,3,4], k = 3
Output: false
Explanation: Each array should be divided in subarrays of size 3.

Constraints:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
1 <= k <= nums.length

class Solution:
    def isPossibleDivide(self, nums: List[int], k: int) -> bool:

        nums.sort()
        counts = collections.Counter(nums)

        for x in nums:
            if counts[x] == 0:
                continue
            exist_chain = True
            for i in range(k):
                if counts[x+i] == 0:
                    return False
                counts[x+i] -= 1

        return True


Solve in Python:
Given an array of ints, return the index such that the sum of the elements to the right of that index equals the sum of the elements to the left of that index. If there is no such index, return `-1`. If there is more than one such index, return the left-most index.

For example:
```
peak([1,2,3,5,3,2,1]) = 3, because the sum of the elements at indexes 0,1,2 == sum of elements at indexes 4,5,6. We don't sum index 3.
peak([1,12,3,3,6,3,1]) = 2
peak([10,20,30,40]) = -1
```

The special case of an array of zeros (for instance `[0,0,0,0]`) will not be tested.

More examples in the test cases.

Good luck!

Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)

def peak(arr):
    left_sum, right_sum = [0], [0]
    for n in arr: left_sum.append(n + left_sum[-1])
    for n in arr[::-1]: right_sum.append(n + right_sum[-1])
    for i in range(len(arr)):
        if right_sum[len(arr)-1-i] == left_sum[i]: return i
    return -1


Solve in Python:
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

Example:

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.

Follow up:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

class Solution:
     def minSubArrayLen(self, s, nums):
         """
         :type s: int
         :type nums: List[int]
         :rtype: int
         """
         if nums is None or len(nums) == 0:
             return 0
         running_sum = [nums[0]]
         for num in nums[1:]:
             running_sum.append(running_sum[-1] + num)
         def sub_sum(i,j):
             to_remove = 0 if i == 0 else running_sum[i-1]
             to_add = 0 if j == 0 else running_sum[j-1]
             return to_add - to_remove
         min_seen = float('inf')
         fast = 0
         slow = 0
         while fast < len(nums):
             while sub_sum(slow, fast) < s and fast < len(nums):
                 fast += 1
             while sub_sum(slow, fast) >= s and slow <= fast:
                 min_seen = min(min_seen, fast - slow)
                 slow += 1
         return 0 if min_seen == float('inf') else min_seen


Solve in Python:
Given an array of n$n$ integers : A1,A2,...,An$ A_1, A_2,... , A_n$, find the longest size subsequence which satisfies the following property: The xor of adjacent integers in the subsequence must be non-decreasing.

-----Input:-----
- First line contains an integer n$n$, denoting the length of the array.
- Second line will contain n$n$ space separated integers, denoting the elements of the array.

-----Output:-----
Output a single integer denoting the longest size of subsequence with the given property.

-----Constraints-----
- 1≤n≤103$1 \leq n \leq 10^3$
- 0≤Ai≤1018$0 \leq A_i \leq 10^{18}$

-----Sample Input:-----
8
1 200 3 0 400 4 1 7

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

-----EXPLANATION:-----
The subsequence of maximum length is {1, 3, 0, 4, 1, 7} with Xor of adjacent indexes as {2,3,4,5,6} (non-decreasing)

n=int(input())
l=list(map(int,input().split()))
a=[]
for i in range(0,n):
    for j in range(i+1,n):
     a.append((l[i]^l[j],(i,j)))

a.sort()
dp=[0]*n
for i in range(0,len(a)):
    x=a[i][0]
    left,right=a[i][1][0],a[i][1][1]
    dp[right]=max(dp[left]+1,dp[right])

print(max(dp)+1)


Solve in Python:
Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.
Notice that you can not jump outside of the array at any time.

Example 1:
Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true
Explanation:
All possible ways to reach at index 3 with value 0 are:
index 5 -> index 4 -> index 1 -> index 3
index 5 -> index 6 -> index 4 -> index 1 -> index 3

Example 2:
Input: arr = [4,2,3,0,3,1,2], start = 0
Output: true
Explanation:
One possible way to reach at index 3 with value 0 is:
index 0 -> index 4 -> index 1 -> index 3

Example 3:
Input: arr = [3,0,2,1,2], start = 2
Output: false
Explanation: There is no way to reach at index 1 with value 0.

Constraints:

1 <= arr.length <= 5 * 10^4
0 <= arr[i] < arr.length
0 <= start < arr.length

class Solution:
    def canReach(self, arr: List[int], start: int) -> bool:
        q = collections.deque()
        visited = set()
        q.append(start)
        visited.add(start)
        while len(q) > 0:
            curr_idx = q.popleft()
            if arr[curr_idx] == 0:
                return True
            for next_idx in [curr_idx + arr[curr_idx], curr_idx - arr[curr_idx]]:
                if 0 <= next_idx < len(arr):
                    if next_idx not in visited:
                        q.append(next_idx)
                        visited.add(next_idx)
        return False


Solve in Python:
Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

class Solution:
     def canJump(self, nums):
         """
         :type nums: List[int]
         :rtype: bool
         """
         if (not nums) or (len(nums) == 1): return True
         status = [False] * (len(nums) - 1) + [True]
         curr = len(nums) - 1
         for j in range(len(nums) - 2, -1, -1):
             if status[min(len(nums) - 1, j + nums[j])]:
                 for i in range(j, curr):
                     status[i] = True
                 curr = j
         return status[0]


Solve in Python:
Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note:

You can assume that you can always reach the last index.

class Solution:
     def jump(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         res = 0
         n = len(nums)
         i, j = 0, 0

         while j < n - 1:
             print((i, j))
             ii, jj = i, j
             for k in range(ii, jj + 1):
                 j = max(j, min(n - 1, k + nums[k]))
             i = jj + 1
             res += 1
         return res


Solve in Python:
Given an array of numbers (in string format), you must return a string. The numbers correspond to the letters of the alphabet in reverse order: a=26, z=1 etc. You should also account for `'!'`, `'?'` and `' '` that are represented by '27', '28' and '29' respectively.

All inputs will be valid.


Solve in Python:
Given an array of numbers, calculate the largest sum of all possible blocks of consecutive elements within the array. The numbers will be a mix of positive and negative values. If all numbers of the sequence are nonnegative, the answer will be the sum of the entire array. If all numbers in the array are negative, your algorithm should return zero. Similarly, an empty array should result in a zero return from your algorithm.

```
largestSum([-1,-2,-3]) == 0
largestSum([]) == 0
largestSum([1,2,3]) == 6
```

Easy, right? This becomes a lot more interesting with a mix of positive and negative numbers:

```
largestSum([31,-41,59,26,-53,58,97,-93,-23,84]) == 187
```

The largest sum comes from elements in positions 3 through 7:
```59+26+(-53)+58+97 == 187```

Once your algorithm works with these, the test-cases will try your submission with increasingly larger random problem sizes.

def largest_sum(arr):
    best_sum = 0
    current_sum = 0
    for item in arr:
        current_sum += item
        if current_sum < 0:
            current_sum = 0
        else:
            if current_sum > best_sum:
                best_sum = current_sum
    return best_sum


Solve in Python:
Given an array of numbers, return a string made up of four parts:

a) a four character 'word', made up of the characters derived from the first two and last two numbers in the array. order should be as read left to right (first, second, second last, last),

b) the same as above, post sorting the array into ascending order,

c) the same as above, post sorting the array into descending order,

d) the same as above, post converting the array into ASCII characters and sorting alphabetically.

The four parts should form a single string, each part separated by a hyphen: '-'

example format of solution: 'asdf-tyui-ujng-wedg'

def sort_transform(a):
    a = [chr(e) for e in a]
    r = sorted(a)
    x = ''.join(r[:2] + r[-2:])
    return '-'.join([''.join(a[:2]+a[-2:]), x, x[::-1], x])


Solve in Python:
Given an array of numbers, return an array, with each member of input array rounded to a nearest number, divisible by 5.

For example:
```
roundToFive([34.5, 56.2, 11, 13]);
```
should return
```
[35, 55, 10, 15]
```

```if:python
Roundings have to be done like "in real life": `22.5 -> 25`
```

def round_to_five(numbers):
    return [int((n + 2.5) / 5) * 5 for n in numbers]


Solve in Python:
Given an array of numbers, return the difference between the largest and smallest values.

For example:

`[23, 3, 19, 21, 16]` should return `20` (i.e., `23 - 3`).

`[1, 434, 555, 34, 112]` should return `554` (i.e., `555 - 1`).

The array will contain a minimum of two elements. Input data range guarantees that `max-min` will cause no integer overflow.

def between_extremes(numbers):
    return max(numbers) - min(numbers)


Solve in Python:
Given an array of one's and zero's that represents a positive binary number convert the number to two's complement value.

Two's complement is the way most computers represent positive or negative integers. The most significant bit is negative.

Examples:

-8 4 2 1

[1,1,1,1] = -1

[1,0,0,0] = -8

[1,1,0,1] = -3

To get the two's complement negative notation of an integer, you take the number in binary.

You then invert the digits, and add one to the result.

For example:

[0,0,1,0] = 2 in base 10

[1,1,0,1] <- Flip the bits

   Add 1

[1,1,1,0] = -2

However, the arrays can have varying lengths, not just limited to 4.

def positive_to_negative(binary):
    binary = [not i for i in binary]
    for i in range(len(binary)-1,-1,-1):
        if binary[i]:
            binary[i] = 0
        else:
            binary[i] = 1
            break

    return binary


Solve in Python:
Given an array of ones and zeroes, convert the equivalent binary value to an integer.

Eg: `[0, 0, 0, 1]` is treated as `0001` which is the binary representation of `1`.

Examples:
```
Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11
```

However, the arrays can have varying lengths, not just limited to `4`.

def binary_array_to_number(arr):
    return int(''.join(str(a) for a in arr), 2)


Solve in Python:
Given an array of positive integers arr,  find a pattern of length m that is repeated k or more times.
A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.
Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.

Example 1:
Input: arr = [1,2,4,4,4,4], m = 1, k = 3
Output: true
Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.

Example 2:
Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2
Output: true
Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.

Example 3:
Input: arr = [1,2,1,2,1,3], m = 2, k = 3
Output: false
Explanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.

Example 4:
Input: arr = [1,2,3,1,2], m = 2, k = 2
Output: false
Explanation: Notice that the pattern (1,2) exists twice but not consecutively, so it doesn't count.

Example 5:
Input: arr = [2,2,2,2], m = 2, k = 3
Output: false
Explanation: The only pattern of length 2 is (2,2) however it's repeated only twice. Notice that we do not count overlapping repetitions.

Constraints:

2 <= arr.length <= 100
1 <= arr[i] <= 100
1 <= m <= 100
2 <= k <= 100

class Solution:
    def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
        for i in range(0, len(arr)-(k-1)*m-m+1):
            found = True
            for j in range(0, m):
                for n in range(1, k):
                    #print(i, j, n, i+j, m*n + i+j)
                    if arr[i+j] != arr[m*n + i+j]:
                        found = False
            if found:
                return True
        return False


Solve in Python:
Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
A subarray is defined as a contiguous block of elements in the array.

Example 1:
Input: nums = [3,1,4,2], p = 6
Output: 1
Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.

Example 2:
Input: nums = [6,3,5,2], p = 9
Output: 2
Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.

Example 3:
Input: nums = [1,2,3], p = 3
Output: 0
Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.

Example 4:
Input: nums = [1,2,3], p = 7
Output: -1
Explanation: There is no way to remove a subarray in order to get a sum divisible by 7.

Example 5:
Input: nums = [1000000000,1000000000,1000000000], p = 3
Output: 0

Constraints:

1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= p <= 109

class Solution:
    def minSubarray(self, nums: List[int], p: int) -> int:
        total = sum(nums)
        remainder = total % p
        if not remainder:
            return 0
        ans = float('inf')
        presum = [0]
        remainders = {0: -1}
        for i, n in enumerate(nums):
            presum.append(presum[-1] + n)
            r = ((cr := presum[-1] % p) - remainder) % p
            if r in remainders:
                ans = min(ans, i - remainders[r])
            remainders[cr] = i
        return ans if ans < len(nums) else -1


Solve in Python:
Given an array of positive integers target and an array initial of same size with all zeros.
Return the minimum number of operations to form a target array from initial if you are allowed to do the following operation:

Choose any subarray from initial and increment each value by one.

The answer is guaranteed to fit within the range of a 32-bit signed integer.

Example 1:
Input: target = [1,2,3,2,1]
Output: 3
Explanation: We need at least 3 operations to form the target array from the initial array.
[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).
[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).
[1,2,2,2,1] increment 1 at index 2.
[1,2,3,2,1] target array is formed.

Example 2:
Input: target = [3,1,1,2]
Output: 4
Explanation: (initial)[0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2] (target).

Example 3:
Input: target = [3,1,5,4,2]
Output: 7
Explanation: (initial)[0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1]
                                  -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2] (target).

Example 4:
Input: target = [1,1,1,1]
Output: 1

Constraints:

1 <= target.length <= 10^5
1 <= target[i] <= 10^5

class Solution:
    def minNumberOperations(self, target: List[int]) -> int:
        result = 0
        last = 0
        for i in range(len(target)):
            if target[i] >= last:
                result += target[i] - last
            last = target[i]
        return result


Solve in Python:
Given an array of positive integers, replace every element with the least greater element to its right.
 If there is no greater element to its right, replace it with -1. For instance, given the array

 `[8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28]`,

 the desired output is

 `[18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1]`.

Your task is to create a function "arrayManip()" that takes in an array as its argument, manipulates the array as described above, then return the resulting array.

Note: Return a new array, rather than modifying the passed array.

def array_manip(array):
    return [min((j for j in array[i+1:] if j > array[i]), default=-1) for i in range(len(array))]


Solve in Python:
Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.
A subarray is a contiguous subsequence of the array.
Return the sum of all odd-length subarrays of arr.

Example 1:
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
Example 2:
Input: arr = [1,2]
Output: 3
Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.
Example 3:
Input: arr = [10,11,12]
Output: 66

Constraints:

1 <= arr.length <= 100
1 <= arr[i] <= 1000

class Solution:
    def sumOddLengthSubarrays(self, arr: List[int]) -> int:
        cur_sum, prefix_sum = 0, [0] * (len(arr) + 1)
        ret = 0
        for i in range(1, len(arr)+1):
            cur_sum += arr[i-1]
            prefix_sum[i] = cur_sum
            for j in range(1, i+1, 2):
                # print([i, j])
                ret += prefix_sum[i] - prefix_sum[i-j]
        return ret


Solve in Python:
Given an array of positive or negative integers

 I= [i1,..,in]

you have to produce a sorted array P of the form

[ [p, sum of all ij of I for which p is a prime factor (p positive) of ij] ...]

P will be sorted by increasing order of the prime numbers.
The final result has to be given as a string in Java, C#, C, C++ and as an array of arrays in other languages.

Example:

```python
I = [12, 15] # result = [[2, 12], [3, 27], [5, 15]]
```

[2, 3, 5] is the list of all prime factors of the elements of I, hence the result.

**Notes:**
- It can happen that a sum is 0 if some numbers are negative!

Example: I = [15, 30, -45]
5 divides 15, 30 and (-45) so 5 appears in the result, the sum of the numbers for which 5 is a factor is 0 so we have [5, 0] in the result amongst others.

- In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings.

def sum_for_list(lst):
    factors = {i for k in lst for i in xrange(2, abs(k)+1) if not k % i}
    prime_factors = {i for i in factors if not [j for j in factors-{i} if not i % j]}
    return [[p, sum(e for e in lst if not e % p)] for p in sorted(prime_factors)]


Solve in Python:
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.

Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.

Example 1:

Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.

Example 2:

Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.

Note:

1
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.

class Solution:
     def PredictTheWinner(self, nums):
         """
         :type nums: List[int]
         :rtype: bool
         """
         # total = sum(nums)
         # memo = {}
         # def score(l, r, t):
         #     if l>r: return 0
         #     if (l, r) not in memo:
         #         memo[(l, r)] = t-min(score(l+1, r, t-nums[l]), score(l, r-1, t-nums[r]))
         #     return memo[(l, r)]
         # sc = score(0, len(nums)-1, total)
         # return sc>=total-sc
         N = len(nums)
         dp = [[0]*N for _ in range(N)]
         pre_sum = [nums[0]]*(N+1)
         pre_sum[-1] = 0
         for i in range(1, N):
             pre_sum[i] = pre_sum[i-1]+nums[i]
         for i in range(N):
             dp[i][i] = nums[i]
         for l in range(1, N):
             for i in range(N-l):
                 dp[i][i+l] = max(pre_sum[i+l]-pre_sum[i-1]-dp[i+1][i+l], pre_sum[i+l]-pre_sum[i-1]-dp[i][i+l-1])
         return dp[0][N-1]*2>=pre_sum[N-1]


Solve in Python:
Given an array of size N$N$ and two integers K$K$ and S$S$, the special sum of a subarray is defined as follows:

(Sum of all elements of the subarray) * (K$K$ - p$p$ * S$S$)

Where p$p$ = number of distinct prime factors of “product of all elements of the subarray”.

Find the maximum special sum by considering all non-empty subarrays of the given array.

-----Input-----
- First line contains 3 integers N$N$, K$K$ and S$S$.
- Second line contains N$N$ integers, the elements of the array.

-----Output-----
Output a single integer. The maximum special sum considering all non-empty subarrays of the array.

-----Constraints:-----
- 1≤N,K,S≤105$ 1 \leq N, K, S \leq 10^5 $
- 0≤K/S≤20$ 0 \leq K / S \leq 20 $
- 1<$ 1 < $ Any element of array <105$ < 10^5 $

-----Sample Input-----
4 10 2

14 2 7 15

-----Sample Output-----
138

-----Sample Explanation-----
Consider the subarray {14, 2, 7}

Total number of distinct prime factors in it is 2 (2 and 7).

Therefore, value of special sum is (14 + 2 + 7) * (10 - 2 * 2) = 138.

This is the subarray with the maximum special sum.

# cook your dish here
from math import floor, sqrt
try:long
except NameError:long = int
def fac(n):
    step,maxq,d = lambda x: 1 + (x<<2) - ((x>>1)<<1),long(floor(sqrt(n))),1
    q = n % 2 == 0 and 2 or 3
    while q <= maxq and n % q != 0:
     q = step(d)
     d += 1
    return q <= maxq and [q] + fac(n//q) or [n]
n,k,s = map(int,input().split())
a,di,l,m,ans,su =list(map(int,input().split())),{},[],0,0,0
for i in a:
    bb,su = list(set(fac(i))),su+i
    for j in bb:
     try:di[j]+=1
     except KeyError:m,di[j] = m+1,1
    l.append(su*(k-m*s))
    if su*(k-m*s) <0:m,di,su = 0,{},0
print(max(l))


Solve in Python:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

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

class Solution:
     def majorityElement(self, nums):
         """
         :type nums: List[int]
         :rtype: int
         """
         if not nums:
             return ""
         current = nums[0]
         counter = 1
         for i in range(1, len(nums)):
             if counter == 0:
                 current = nums[i]
                 counter = 1
             elif nums[i] == current:
                 counter += 1
             else:
                 counter -= 1
         return current


Solve in Python:
Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters.
Return the maximum possible length of s.

Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.

Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible solutions are "chaers" and "acters".

Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26

Constraints:

1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i] contains only lower case English letters.

from collections import Counter
class Solution:
    def maxLength(self, arr: List[str]) -> int:
        max_str = 0
        for i in range(len(arr)):
            if self.is_unique(arr[i]) and len(arr[i]) > max_str:
                max_str = len(arr[i])

            concat = [arr[i]]
            for j in range(i+1, len(arr)):
                for x in concat:
                    c = x + arr[j]
                    if self.is_unique(c):
                        if len(c) > max_str:
                            max_str = len(c)
                        concat.append(c)
        return max_str

    def is_unique(self, str):
        for v in Counter(str).values():
            if v > 1:
                return False
        return True


Solve in Python:
Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].
Since two files cannot have the same name, if you enter a folder name which is previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique.
Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.

Example 1:
Input: names = ["pes","fifa","gta","pes(2019)"]
Output: ["pes","fifa","gta","pes(2019)"]
Explanation: Let's see how the file system creates folder names:
"pes" --> not assigned before, remains "pes"
"fifa" --> not assigned before, remains "fifa"
"gta" --> not assigned before, remains "gta"
"pes(2019)" --> not assigned before, remains "pes(2019)"

Example 2:
Input: names = ["gta","gta(1)","gta","avalon"]
Output: ["gta","gta(1)","gta(2)","avalon"]
Explanation: Let's see how the file system creates folder names:
"gta" --> not assigned before, remains "gta"
"gta(1)" --> not assigned before, remains "gta(1)"
"gta" --> the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)"
"avalon" --> not assigned before, remains "avalon"

Example 3:
Input: names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]
Output: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]
Explanation: When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)".

Example 4:
Input: names = ["wano","wano","wano","wano"]
Output: ["wano","wano(1)","wano(2)","wano(3)"]
Explanation: Just increase the value of k each time you create folder "wano".

Example 5:
Input: names = ["kaido","kaido(1)","kaido","kaido(1)"]
Output: ["kaido","kaido(1)","kaido(2)","kaido(1)(1)"]
Explanation: Please note that system adds the suffix (k) to current name even it contained the same suffix...

class Solution:
    def getFolderNames(self, names) :
        res = []
        allname = collections.Counter()
        # print(names)
        for name in names:
            if name in allname:
                while f'{name}({allname[name]})' in allname:
                    allname[name] += 1
                res.append(f'{name}({allname[name]})')
                allname[f'{name}({allname[name]})'] = 1
            else:
                allname[name] = 1
                res.append(name)
        return res


Solve in Python:
Given an array of unique integers salary where salary[i] is the salary of the employee i.
Return the average salary of employees excluding the minimum and maximum salary.

Example 1:
Input: salary = [4000,3000,1000,2000]
Output: 2500.00000
Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000)/2= 2500

Example 2:
Input: salary = [1000,2000,3000]
Output: 2000.00000
Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000)/1= 2000

Example 3:
Input: salary = [6000,5000,4000,3000,2000,1000]
Output: 3500.00000

Example 4:
Input: salary = [8000,9000,2000,3000,6000,1000]
Output: 4750.00000

Constraints:

3 <= salary.length <= 100
10^3 <= salary[i] <= 10^6
salary[i] is unique.
Answers within 10^-5 of the actual value will be accepted as correct.

class Solution:
    def average(self, arr: List[int]) -> float:
        return (sum(arr)-min(arr)-max(arr))/(len(arr)-2)


Solve in Python:
Given an array of unique integers, each integer is strictly greater than 1.
We make a binary tree using these integers and each number may be used for any number of times.
Each non-leaf node's value should be equal to the product of the values of it's children.
How many binary trees can we make?  Return the answer modulo 10 ** 9 + 7.
Example 1:
Input: A = [2, 4]
Output: 3
Explanation: We can make these trees: [2], [4], [4, 2, 2]
Example 2:
Input: A = [2, 4, 5, 10]
Output: 7
Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].

Note:

1 <= A.length <= 1000.
2 <= A[i] <= 10 ^ 9.

class Solution:
    def numFactoredBinaryTrees(self, A: List[int]) -> int:
        A = sorted(A)
        mems = {}
        for ix in range(len(A)):
            mems[A[ix]] = ix

        dp = [1] * len(A)

        big_mod = 10**9 + 7

        for i in range(len(A)):
            extras = 0
            for j in range(i):
                d, mo = divmod(A[i], A[j])
                if mo == 0:
                    if d in mems:
                        extras += dp[j] * dp[mems[d]]
                        extras = extras % big_mod

            dp[i] += extras

        result = sum(dp) % big_mod

        return result


Solve in Python:
Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

Note:

       A word is defined as a character sequence consisting of non-space characters only.
       Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
       The input array words contains at least one word.

Example 1:

Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]

Example 2:

Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
Explanation: Note that the last line is "shall be    " instead of "shall     be",
             because the last line must be left-justified instead of fully-justified.
             Note that the second line is also left-justified becase it contains only one word.

Example 3:

Input:
words = ["Science","is","what","we","understand","well","enough","to","explain",
         "to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]

class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         if maxWidth == 0:
             return [" ".join(words)]
         words = words[:]
         results = []
         while words:
             run = []
             c = 0
             while words:
                 pad = 1 if run else 0
                 if len(words[0]) + pad + c > maxWidth:
                     spaces = maxWidth - sum([len(w) for w in run])
                     if len(run) == 1:
                         line = "".join(run + [" "] * spaces)
                         assert len(line) == maxWidth
                         results.append(line)
                     else:
                         eachSpace = spaces // (len(run) - 1)
                         extraSpaces = spaces % (len(run) - 1)
                         line = []
                         for i in range(len(run)):
                             line.append(run[i])
                             if i != len(run) - 1:
                                 line.append(' ' * eachSpace)
                                 if extraSpaces > 0:
                                     line.append(' ')
                                     extraSpaces -= 1
                         line = "".join(line)
                         assert len(line) == maxWidth, len(line)
                         results.append(line)
                     break
                 else:
                     if run:
                         c += 1
                     w = words.pop(0)
                     run.append(w)
                     c += len(w)
         if run:
             line = " ".join(run)
             line += ' ' * (maxWidth - len(line))
             results.append(line)
         return results


Solve in Python:
Given an array of integers arr and an integer d. In one step you can jump from index i to index:

i + x where: i + x < arr.length and  0 < x <= d.
i - x where: i - x >= 0 and  0 < x <= d.

In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).
You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.
Notice that you can not jump outside of the array at any time.

Example 1:

Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2
Output: 4
Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
Similarly You cannot jump from index 3 to index 2 or index 1.

Example 2:
Input: arr = [3,3,3,3,3], d = 3
Output: 1
Explanation: You can start at any index. You always cannot jump to any index.

Example 3:
Input: arr = [7,6,5,4,3,2,1], d = 1
Output: 7
Explanation: Start at index 0. You can visit all the indicies.

Example 4:
Input: arr = [7,1,7,1,7,1], d = 2
Output: 2

Example 5:
Input: arr = [66], d = 1
Output: 1

Constraints:

1 <= arr.length <= 1000
1 <= arr[i] <= 10^5
1 <= d <= arr.length

class Solution:

    def maxJumps(self, arr: List[int], d: int) -> int:

        n = len(arr)
        res = [0] * n

        def dp(i):
            if res[i]: return res[i]
            res[i] = 1
            for di in [-1, 1]:
                for j in range(i+di, i+di+d*di, di):
                    if not (0 <= j < n and arr[j] < arr[i]):
                        break
                    res[i] = max(res[i], dp(j)+1)
            return res[i]

        return max(map(dp, range(n)))


Solve in Python:
Given an array of integers arr, you are initially positioned at the first index of the array.
In one step you can jump from index i to index:

i + 1 where: i + 1 < arr.length.
i - 1 where: i - 1 >= 0.
j where: arr[i] == arr[j] and i != j.

Return the minimum number of steps to reach the last index of the array.
Notice that you can not jump outside of the array at any time.

Example 1:
Input: arr = [100,-23,-23,404,100,23,23,23,3,404]
Output: 3
Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.

Example 2:
Input: arr = [7]
Output: 0
Explanation: Start index is the last index. You don't need to jump.

Example 3:
Input: arr = [7,6,9,6,9,6,9,7]
Output: 1
Explanation: You can jump directly from index 0 to index 7 which is last index of the array.

Example 4:
Input: arr = [6,1,9]
Output: 2

Example 5:
Input: arr = [11,22,7,7,7,7,7,7,7,22,13]
Output: 3

Constraints:

1 <= arr.length <= 5 * 10^4
-10^8 <= arr[i] <= 10^8

import collections
class Solution:
    def minJumps(self, arr: List[int]) -> int:
        if len(arr) == 1:
            return 0

        d = collections.defaultdict(list)
        for index, element in enumerate(arr):
            d[element].append(index)

        queue = collections.deque([(0, 0)])
        s = set()
        s.add(0)

        while len(queue):
            currIndex, jumps = queue.popleft()

            for nextIndex in [currIndex + 1, currIndex - 1] + d[arr[currIndex]][::-1]:
                if nextIndex < len(arr) and nextIndex > -1 and nextIndex != currIndex and nextIndex not in s:
                    if nextIndex == len(arr) - 1:
                        return jumps + 1
                    s.add(nextIndex)
                    queue.append((nextIndex, jumps + 1))

        return -1


Solve in Python:
Given an array of integers arr.
We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).
Let's define a and b as follows:

a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]

Note that ^ denotes the bitwise-xor operation.
Return the number of triplets (i, j and k) Where a == b.

Example 1:
Input: arr = [2,3,1,6,7]
Output: 4
Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)

Example 2:
Input: arr = [1,1,1,1,1]
Output: 10

Example 3:
Input: arr = [2,3]
Output: 0

Example 4:
Input: arr = [1,3,5,7,9]
Output: 3

Example 5:
Input: arr = [7,11,12,9,5,2,7,17,22]
Output: 8

Constraints:

1 <= arr.length <= 300
1 <= arr[i] <= 10^8

class Solution:
    def countTriplets(self, arr: List[int]) -> int:
        preXor = [0] * (len(arr) + 1)
        preXor[0] = arr[0]
        for i in range(1, len(arr)):
            preXor[i] = preXor[i-1] ^ arr[i]
        ret = 0
        for i in range(len(arr)-1):
            for j in range(i+1, len(arr)):
                l = preXor[i-1]
                for k in range(j, len(arr)):
                    #print(i, j, k)
                    if l == preXor[k]:
                        #print(\"match:\", i, j, k)
                        ret += 1
        return ret


Solve in Python:
Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.

Note:
If n is the length of array, assume the following constraints are satisfied:

1 ≤ n ≤ 1000
1 ≤ m ≤ min(50, n)

Examples:

Input:
nums = [7,2,5,10,8]
m = 2

Output:
18

Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.

class Solution:
     def splitArray(self, pages, k):
         """
         :type nums: List[int]
         :type m: int
         :rtype: int
         """
         if not pages or k == 0:
             return 0

         pre = sums = [0] + pages[:]
         for i in range(1, len(sums)):
             sums[i] += sums[i-1]

         for n in range(2, k + 1):
             if n > len(pages):
                 break

             cur = [sys.maxsize] * len(pre)
             i, j = n - 1, n
             while j < len(pre):
                 left, right = pre[i], sums[j] - sums[i]
                 cur[j] = min(cur[j], max(left, right))
                 if i + 1 < j and max(pre[i+1], sums[j] - sums[i+1]) < cur[j]:
                     i += 1
                 else:
                     j += 1

             pre = cur

         return pre[-1]


Solve in Python:
Given an array with exactly 5 strings `"a"`, `"b"` or `"c"` (`char`s in Java, `character`s in Fortran), check if the array contains three and two of the same values.

## Examples

```
["a", "a", "a", "b", "b"] ==> true  // 3x "a" and 2x "b"
["a", "b", "c", "b", "c"] ==> false // 1x "a", 2x "b" and 2x "c"
["a", "a", "a", "a", "a"] ==> false // 5x "a"
```

def check_three_and_two(array):
    return len(set(array)) == 2 and array.count(array[0]) not in [1,4]


Solve in Python:
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if array[i]  holds for every i (1

Example 1:

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.

Note:
The n belongs to [1, 10,000].

class Solution:
     def checkPossibility(self, nums):
         """
         :type nums: List[int]
         :rtype: bool
         """
         count  = 0
         if len(nums) == 1:
             return True
         for i in range(0,len(nums)-1):
             if nums[i] > nums[i+1]:
                 if nums[i+1] < nums[i-1] and i-1 >= 0:
                     count += 1
                     if count > 1:
                         break
                     if i+1 != (len(nums)-1):
                         nums[i+1] = nums[i]
                 else:
                     nums[i] = nums[i+1]
                     count += 1
                     if count > 1:
                         break
                     if count == 1:
                         nums[i] -= 1

         if count > 1:
             return False
         else:
             return True


Solve in Python:
Given an array, find the duplicates in that array, and return a new array of those duplicates. The elements of the returned array should appear in the order when they first appeared as duplicates.

__*Note*__: numbers and their corresponding string representations should not be treated as duplicates (i.e., `"1" != 1`).

## Examples
```
[1, 2, 4, 4, 3, 3, 1, 5, 3, "5"]  ==>  [4, 3, 1]
[0, 1, 2, 3, 4, 5]                ==>  []
```

def duplicates(arr):
    res = []
    for i, x in enumerate(arr):
        if arr[:i + 1].count(x) > 1 and x not in res:
            res.append(x)
    return res


Solve in Python:
Given an array, return the difference between the count of even numbers and the count of odd numbers. `0` will be considered an even number.

```
For example:
solve([0,1,2,3]) = 0 because there are two even numbers and two odd numbers. Even - Odd = 2 - 2 = 0.
```

Let's now add two letters to the last example:
```
solve([0,1,2,3,'a','b']) = 0. Again, Even - Odd = 2 - 2 = 0. Ignore letters.
```

The input will be an array of lowercase letters and numbers only.

In some languages (Haskell, C++, and others), input will be an array of strings:

```
solve ["0","1","2","3","a","b"] = 0
```

Good luck!

If you like this Kata, please try:

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

[Word values](https://www.codewars.com/kata/598d91785d4ce3ec4f000018)

def solve(a):
    diff = 0
    for e in a:
        if type(e) == int:
            if e % 2:
                diff -= 1
            else:
                diff += 1
    return diff


Solve in Python:
Given an array, return the reversed version of the array (a different kind of reverse though), you reverse portions of the array, you'll be given a length argument which represents the length of each portion you are to reverse.

E.g

  if after reversing some portions of the array and the length of the remaining portion in the array is not up to the length argument, just reverse them.

`selReverse(array, length)`

- array - array to reverse
- length - length of each portion to reverse

Note : if the length argument exceeds the array length, reverse all of them, if the length argument is zero do not reverse at all.

def sel_reverse(arr,l):
    return sum([arr[i:i+l][::-1] for i in range(0,len(arr),l)],[]) if l>0 else arr


Solve in Python:
Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.
24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.
Return the latest 24-hour time in "HH:MM" format.  If no valid time can be made, return an empty string.

Example 1:
Input: A = [1,2,3,4]
Output: "23:41"
Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest.

Example 2:
Input: A = [5,5,5,5]
Output: ""
Explanation: There are no valid 24-hour times as "55:55" is not valid.

Example 3:
Input: A = [0,0,0,0]
Output: "00:00"

Example 4:
Input: A = [0,0,1,0]
Output: "10:00"

Constraints:

arr.length == 4
0 <= arr[i] <= 9

from itertools import permutations

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

        arr = sorted(arr, reverse=True)

        perms = permutations(arr)

        for perm in perms:
            m = perm[0] * 10 + perm[1]
            s = perm[2] * 10 + perm[3]

            if m < 24 and s < 60:
                strm = str(m)
                strs = str(s)
                if len(strm) < 2:
                    strm = \"0\" + strm
                if len(strs) < 2:
                    strs = \"0\" + strs
                return \"{}:{}\".format(strm, strs)

        return \"\"


Solve in Python:
Given an array nums of integers, we need to find the maximum possible sum of elements of the array such that it is divisible by three.

Example 1:
Input: nums = [3,6,5,1,8]
Output: 18
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
Example 2:
Input: nums = [4]
Output: 0
Explanation: Since 4 is not divisible by 3, do not pick any number.

Example 3:
Input: nums = [1,2,3,4,4]
Output: 12
Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).

Constraints:

1 <= nums.length <= 4 * 10^4
1 <= nums[i] <= 10^4

class Solution:
    def maxSumDivThree(self, nums: List[int]) -> int:

        n = len(nums)
        dp = [[0]*3 for _ in range(n)]

        for i, x in enumerate(nums):
            m = x % 3
            if i > 0:
                dp[i] = dp[i-1][::]
                # for j in range(3):
                #     if dp[i][(j-m)%3] > 0:
                #         dp[i][j] = max(dp[i][j], dp[i][(x-m)%3] + x)
                rot = [dp[i][(x-m)%3] for x in range(3)]

                for j in range(3):
                    if rot[j] > 0:
                        dp[i][j] = max(dp[i][j], rot[j] + x) # can add to it

            dp[i][m] = max(dp[i][m], x) # better to start anew with current element

        print(dp)
        return dp[-1][0]


Solve in Python:
Given an empty array A of infinite length and a positive integer K you have to process
Q queries of type:
- ! l r x: Fill the value x in all the empty places in the array from index l to r  (both inclusive).
- ? l r: Print the number of prime factors of K which is also a prime factor of at least one number in A[l], A[l + 1], A[l + 2], … A[r].

-----Input-----
- The first line contains two space separated integers K and Q respectively.
- Then Q lines follow:
- Each of the $i^{th}$ line contains one of the above two types of queries.

-----Output-----
For each query of the second type, print in a new line the answer to that query. i.e. number of prime factors of K which is also a prime factor of at least one number in A[l], A[l + 1], A[l + 2], … A[r].

-----Constraints-----
- $1 \leq K, x \leq 10^9$
- $ 1 \leq l \leq r \leq 10^5$
- $ 1 \leq Q \leq 10^5$

-----Sample Input-----
20 5

? 1 5

! 3 5 4

? 1 5

! 1 4 15

? 1 5

-----Sample Output-----
0

1

2

-----EXPLANATION-----
Initially, all the places in the array are empty. i.e _ _ _ _ _

After first update the array looks like: _ _ 4 4 4

In the range [1, 5] the only factor of 20 which is also a prime factor of at least one number in _ _ 4 4 4  is 2.

After the second update the array looks like: 15 15 4 4 4

In the range [1, 5] the prime factors of 20 i.e. 5 is a prime factor of 15, 15 and 2 is the prime factor of 4, 4, 4.

import math
def distinctPrimeFactors(num) :
    primes,sqrt = set(),int(math.sqrt(num))
    if (num == 2) :primes.add(num)
    for j in range(2, sqrt + 1) :
        if (num % j == 0) :
            primes.add(j)
            while (num % j == 0) :num //= j
    if (num > 2) :primes.add(num)
    return (primes)
res,c,lst,primes,rangeData = [],0,{},{},{};k, q = map(int, input().split());primes[k] = distinctPrimeFactors(k)
for tc in range(q) :
    query = input()
    if (query[0] == '!') :
        cmd, l, r, x = query.split();l,r,x = int(l),int(r),int(x);start,end,startflag = l,r,False
        for i in sorted(rangeData) :
            rangeVal = i
            if (start > rangeVal[1]) :continue
            if (end < rangeVal[0]) :break
            startRange,endRange = start,end
            if (start >= rangeVal[0] and start <= rangeVal[1]) :start = rangeVal[1] + 1;continue
            if (end >= rangeVal[0]) :endRange = rangeVal[0] - 1
            if (startRange <= endRange) :
                rangeData[(startRange, endRange)] = x;start = max(endRange + 1, rangeVal[1] + 1)
        if (start <= end) :rangeData[(start,end)] = x
    elif (query[0] == '?') :
        cmd, l, r = query.split();l,r,count = int(l),int(r),0
        for primenum in primes[k] :
            for currRange in rangeData :
                if (not (r < currRange[0] or l > currRange[1])) :
                    if (rangeData[currRange] % primenum == 0) :count += 1;break
        c += 1;res.append(count)
for i in range(c):print(res[i])


Solve in Python:
Given an encoded string, return it's decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

class Solution:
     def decodeString(self, s):
         """
         :type s: str
         :rtype: str
         """
         stack = []
         stack.append(["", 1])
         num = ""
         for ch in s:
             if ch.isdigit():
                 num += ch
             elif ch == '[':
                 stack.append(["", int(num)])
                 num = ""
             elif ch == ']':
                 st, k = stack.pop()
                 stack[-1][0] += st*k
             else:
                 stack[-1][0] += ch
         return stack[0][0]

 # def decodeString(self, s):
 #     while '[' in s:
 #         s = re.sub(r'(\d+)\[([a-z]*)\]', lambda m: int(m.group(1)) * m.group(2), s)
 #     return s


Solve in Python:
Given an equation, represented by words on left side and the result on right side.
You need to check if the equation is solvable under the following rules:

Each character is decoded as one digit (0 - 9).
Every pair of different characters they must map to different digits.
Each words[i] and result are decoded as one number without leading zeros.
Sum of numbers on left side (words) will equal to the number on right side (result).

Return True if the equation is solvable otherwise return False.

Example 1:
Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" ,  9567 + 1085 = 10652
Example 2:
Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" ,  650 + 68782 + 68782 = 138214
Example 3:
Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true

Example 4:
Input: words = ["LEET","CODE"], result = "POINT"
Output: false

Constraints:

2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result contains only upper case English letters.
Number of different characters used on the expression is at most 10.

class Solution:
    def isSolvable(self, words: List[str], result: str) -> bool:
        n = len(words)
        mapper = {}
        maxlen = 0
        for w in words:
            maxlen = max(maxlen, len(w))
            for c in w:
                mapper[c] = -1
        if len(result) < maxlen or len(result) - maxlen > 1:
            return False
        for c in result:
            mapper[c] = -1
        used = [0] * 10
        def solve(i, j, s):
            if j == n:
                l = len(result) - i
                if l < 0:
                    if s != 0:
                        return False
                    if any(mapper[w[0]] == 0 for w in words):
                        return False
                    if mapper[result[0]] == 0:
                        return False
                    return True
                c, s = divmod(s, 10)
                if mapper[result[l]] >= 0:
                    if mapper[result[l]] == s:
                        return solve(i + 1, 0, c)
                    return False
                if used[s]:
                    return False
                mapper[result[l]] = s
                used[s] = 1
                res = solve(i + 1, 0, c)
                mapper[result[l]] = -1
                used[s] = 0
                return res
            w = words[j]
            l = len(w) - i
            if l < 0:
                return solve(i, j + 1, s)
            if mapper[w[l]] >= 0:
                return solve(i, j + 1, s + mapper[w[l]])
            for k in range(10):
                if used[k]:
                    continue
                used[k] = 1
                mapper[w[l]] = k
                if solve(i, j + 1, s + k):
                    return True
                used[k] = 0
                mapper[w[l]] = -1
            return False
        return solve(1, 0, 0)


Solve in Python:
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

Note:

       s could be empty and contains only lowercase letters a-z.
       p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

class Solution:
     def isMatch(self, s, p):
         """
         :type s: str
         :type p: str
         :rtype: bool
         """

         self.mem = {}
         self.t = s
         self.p = p

         return self.match(0,0)

     def match(self, i, j):

         if (i,j) not in self.mem:
             if j == len(self.p):
                 res = i == len(self.t)

             else:
                 if j+1 < len(self.p) and self.p[j+1] == '*':
                     res = self.match(i, j+2) or (i < len(self.t) and self.p[j] in {self.t[i], '.'} and self.match(i+1, j))
                 else:
                     res = i < len(self.t) and self.p[j] in {self.t[i], '.'} and self.match(i+1, j+1)

             self.mem[i, j] = res

         return self.mem[i, j]


Solve in Python:
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

Note:

       s could be empty and contains only lowercase letters a-z.
       p could be empty and contains only lowercase letters a-z, and characters like ? or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Example 4:

Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".

Example 5:

Input:
s = "acdcb"
p = "a*c?b"
Output: false

class Solution:
     def isMatch(self, s, p):
         """
         :type s: str
         :type p: str
         :rtype: bool
         """
         len_s = len(s)
         len_p = len(p)

         if len_s == 0 and len_p == 0:
             return True
         elif len_p == 0:
             return False
         elif len_p == p.count('*'):
             return True
         elif len_p - p.count('*') > len_s:
             return False

         i_s = 0
         i_p = 0
         star_index = None
         s_star_match = None

         while i_s < len_s:
             pchar = p[i_p] if i_p < len_p else None
             schar = s[i_s]
             if pchar == '*':
                 star_index = i_p
                 s_star_match = i_s
                 i_p += 1
             elif pchar == '?' or pchar == schar:
                 i_s +=1
                 i_p += 1
             elif star_index is not None:
                 i_p = star_index + 1
                 s_star_match += 1
                 i_s = s_star_match
             else:
                 return False
         while i_p < len_p and p[i_p] == '*':
             i_p += 1
         return i_p == len_p