Program to find number of ways we can merge two lists such that ordering does not change in Python

PythonServer Side ProgrammingProgramming

Suppose we have two lists nums1 and nums2. Now the constraint is when we merge the order of elements in each list does not change, for example, if the elements are [1,2,3] and [4,5,6], then some valid merged lists are [1,4,2,3,5,6] and [1,2,3,4,5,6], there may be some other valid merge sequence. So if we have the size of lists N and M. We have to find number of ways we can merge them to get valid list. If the answer is too large the return result modulo 10^9 + 7.

So, if the input is like N = 5 M = 3, then the output will be 56

To solve this, we will follow these steps −

  • ret := 1
  • for i in range N + 1 to N + M, do
    • ret := ret * i
  • for i in range 1 to M, do
    • ret := floor of r/i
  • return ret mod (10^9 + 7)

Example

Let us see the following implementation to get better understanding −

def solve(N, M):
   ret = 1
   for i in range(N + 1, N + M + 1):
      ret *= i
   for i in range(1, M + 1):
      ret //= i
   return ret % (10**9 + 7)

N = 5
M = 3
print(solve(N, M))

Input

5, 3

Output

56
raja
Updated on 25-Oct-2021 06:30:58

Advertisements