Program to count number of possible humble matrices in Python

Suppose we have two values n and m. We have to find the number of possible arrangements of humble matrices of order n × m. A matrix is said to be humble when:

  • It contains each element in range 1 to n × m exactly once
  • For any two indices pairs (i1, j1) and (i2, j2), if (i1 + j1) < (i2 + j2), then Mat[i1, j1] < Mat[i2, j2] should hold

If the answer is too large, return the result modulo 109 + 7.

Understanding Humble Matrices

A humble matrix has elements arranged such that values increase along anti-diagonals. For a 2×2 matrix, there are two valid arrangements ?

1 2
3 4

And:

1 3
2 4

Algorithm

To solve this problem, we follow these steps ?

  • Pre-compute factorials up to 106 to handle large calculations efficiently
  • Ensure m ? n by swapping if necessary
  • Calculate the product using the mathematical formula for humble matrices
  • Apply modulo arithmetic to prevent overflow

Implementation

def count_humble_matrices(n, m):
    p = 10**9 + 7
    
    # Pre-compute factorials
    factorials = [1]
    for x in range(2, 10**6 + 1):
        temp = factorials[-1]
        temp = (temp * x) % p
        factorials.append(temp)
    
    # Ensure m <= n
    if m > n:
        n, m = m, n
    
    # Calculate the product
    prod = 1
    for x in range(1, m):
        prod = (prod * factorials[x - 1]) % p
    
    prod = (prod * prod) % p  # Square the product
    
    for x in range(n - m + 1):
        prod = (prod * factorials[m - 1]) % p
    
    return prod

# Test with example
n, m = 2, 2
result = count_humble_matrices(n, m)
print(f"Number of humble matrices for {n}x{m}: {result}")

# Test with larger example
n, m = 3, 3
result = count_humble_matrices(n, m)
print(f"Number of humble matrices for {n}x{m}: {result}")
Number of humble matrices for 2x2: 2
Number of humble matrices for 3x3: 24

How It Works

The algorithm uses combinatorial mathematics to count valid arrangements:

  • Factorial pre-computation: Stores factorials up to 106 for efficient access
  • Matrix normalization: Ensures m ? n to simplify calculations
  • Product calculation: Uses the mathematical formula specific to humble matrices
  • Modulo arithmetic: Prevents integer overflow for large results

Key Points

  • Time complexity: O(max(n,m)) after factorial pre-computation
  • Space complexity: O(106) for storing factorials
  • The constraint (i1 + j1) < (i2 + j2) defines anti-diagonal ordering
  • Modulo 109 + 7 is used to handle large numbers

Conclusion

This solution efficiently counts humble matrices using pre-computed factorials and modular arithmetic. The key insight is recognizing the anti-diagonal constraint pattern and applying the corresponding combinatorial formula.

Updated on: 2026-03-26T18:12:49+05:30

249 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements