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

Suppose we have two lists nums1 and nums2. When we merge them, the constraint is that 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]. We need to find the number of ways we can merge two lists of sizes N and M to get a valid merged list. If the answer is too large, return the result modulo 10^9 + 7.

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

Algorithm

This problem is equivalent to finding the number of ways to choose M positions out of N+M total positions for the second list, which is the combination C(N+M, M). 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 ret/i
  • return ret mod (10^9 + 7)

Example

Let us see the following implementation to get better understanding ?

def solve(N, M):
    ret = 1
    # Calculate (N+M)! / N! = (N+1) * (N+2) * ... * (N+M)
    for i in range(N + 1, N + M + 1):
        ret *= i
    # Divide by M! = 1 * 2 * ... * M
    for i in range(1, M + 1):
        ret //= i
    return ret % (10**9 + 7)

N = 5
M = 3
result = solve(N, M)
print(f"Number of ways to merge lists of size {N} and {M}: {result}")
Number of ways to merge lists of size 5 and 3: 56

How It Works

The solution calculates the binomial coefficient C(N+M, M) using the formula:

  • First, we multiply numbers from (N+1) to (N+M) to get (N+M)!/N!
  • Then, we divide by M! to get the final result C(N+M, M)
  • This approach avoids calculating large factorials directly

Alternative Implementation Using Math Module

import math

def solve_alternative(N, M):
    # Using math.comb for combination calculation
    result = math.comb(N + M, M)
    return result % (10**9 + 7)

N = 5
M = 3
result = solve_alternative(N, M)
print(f"Using math.comb: {result}")
Using math.comb: 56

Conclusion

The number of ways to merge two lists while preserving order is given by the binomial coefficient C(N+M, M). The iterative approach avoids large factorial calculations and provides an efficient solution modulo 10^9 + 7.

Updated on: 2026-03-26T18:21:05+05:30

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements