Program to find number of ways we can arrange letters such that each prefix and suffix have more Bs than As in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string with n number of A's and 2n number of B's. We have to find number of arrangements possible such that in each prefix and each suffix have number of B's greater than or equal to the number of A's

So, if the input is like n = 2, then the output will be 4 because there are two A's and four B's, so possible arrangements are [BBAABB, BABABB, BBABAB, BABBAB].

To solve this, we will follow these steps −

  • Define a method solve, this will take n
  • if n is same as 1, then
    • return 1
  • if n is same as 2, then
    • return 4
  • if n is odd, then
    • return find(floor of (n-1)/2)^2
  • otherwise,
    • return find(floor of n/2)^2


Let us see the following implementation to get better understanding −

def solve(n):
   if n==1:
      return 1
   if n==2:
      return 4
   if n%2 != 0:
      return solve((n-1)//2)**2
      return solve(n//2)**2

n = 2




Updated on 25-Oct-2021 06:52:37