Strings in Java
Date: Sep 2014
Level: Advanced


INTERVIEW QUESTIONS

Company: Directi
Question Title: Strings in Java
Language: Java
QUESTION DETAILS:

We need to make a string of size n. Each character of the string is either 'R', 'B' or 'G'. In the final string there needs to be at least r number of 'R', at least b number of 'B' and at least g number of 'G' (such that r + g + b <= n). We need to find number of such strings possible.
For example,
n = 4, r = 1, b = 1, g = 1.
Output:
36


Here's the code:
import java.util.HashMap;
public class RGB {
public static HashMap<Integer,Long> factorialCache=new HashMap();
	public static void main(String[] args) {
		// TODO Auto-generated method stub
int r=2,g=2,b=1,n=5;
int e=n-(r+g+b),count=0;
factorialCache.put(1,Long.parseLong("1"));
for(int i=2;i<=n;i++)
{
long f=i*factorialCache.get(i-1);
	factorialCache.put(i,f);
}
for(int i=0;i<=e;i++)
{
	for(int j=0;j<=e;j++)
	{
		{
			int k=e-(i+j);
			if(k<0) continue;
			else
			count+=ways(r+i,g+j,b+k,n);
		}
			
	}
}
System.out.print(count);
}

	
	public static long ways(int r,int g,int b,int n)
	{
		return ((factorialCache.get(n)/factorialCache.get(r))/factorialCache.get(g))/factorialCache.get(b);
	}}
All Questions