Program to find number of sequences after adjacent k swaps and at most k swaps in Python


Suppose we have an array A with first n natural numbers. We have to find how many sequences (S1) can we get after exact k adjacent swaps on A? And how many sequences (S2) can we get after at most k swaps on A? Here the adjacent swap means swapping elements at index i and i+1.

So, if the input is like n = 3 k = 2, then the output will be 3, 6 because −

Original array was [1, 2, 3]

  • After 2 adjacent swaps: we can get [1, 2, 3], [2, 3, 1], [3, 1, 2] So S1 = 3
  • After at most 2 swaps:
    • After 0 swap: [1, 2, 3]
    • After 1 swap: [2, 1, 3], [3, 2, 1], [1, 3, 2].
    • After 2 swaps: [1, 2, 3], [2, 3, 1], [3, 1, 2]

So S2 = 6

To solve this, we will follow these steps −

  • p = 10^9+7
  • A := an array with only one element 1
  • C := an array with only one element 1
  • for n in range 2 to n+1, do
    • B := A, A := an array with only one element 1
    • D := C, C := an array with only one element 1
    • for x in range 1 to minimum of (k+1 and sum of all numbers from 1 to n)
      • insert(last element of A + (B[x] when x < size of B otherwise 0) - (B[x-n] when 0 <= x-n otherwise 0)) mod p) at the end of A
    • for x in range 1 to n-2, do
      • insert ((D[x]+(n-1)*D[x-1]) mod p) at the end of C
    • insert (n * last element of D) mod p at the end of C
  • return sum of all elements of A[from index k mod 2 to k]) mod p and C[minimum of n-1 and k]

Example

Let us see the following implementation to get better understanding −

p = 10**9+7
def solve(n, k):
   A = [1]
   C = [1]
   for n in range(2,n+1):
      B = A
      A = [1]
      D = C
      C = [1]

      for x in range(1,min(k+1,n*(n-1)//2+1)):
         A.append((A[-1] + (B[x] if x<len(B) else 0) - (B[x-n] if 0<=x-n else 0)) % p )
      for x in range(1,n-1):
         C.append((D[x]+(n-1)*D[x-1]) % p)
      C.append(n*D[-1] % p)
   return sum(A[k%2:k+1:2]) % p,C[min(n-1,k)]

n = 3
k = 2
print(solve(n, k))

Input

3, 2

Output

3, 6

Updated on: 23-Oct-2021

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements