We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
O(m^2) solution. If you're working in Java, the BigInteger class is very useful for efficient modular power operations. Basically, find all the possible permutations of a single row, then, for each wall width, find all the invalid walls and subtract from all possible walls using DP.
publicstaticlonglegoBlocks(intn,intm){intmod=1000000007;// trivial casesif(m==1){return1;}if(n==1&&m<=4){return1;}if(n==1){return0;}if(m==2){BigIntegerexp=newBigInteger(Integer.toString(n));BigIntegernewMod=newBigInteger(Integer.toString(mod));BigIntegerbase=newBigInteger("2");longresult=(long)base.modPow(exp,newMod).longValue()-1;returnresult;}// Total Permutations of a single rowlong[]totalWays=newlong[m+1];for(inti=0;i<=m;i++){if(i<=1){totalWays[i]=1;continue;}if(i==2){totalWays[i]=2;continue;}if(i==3){totalWays[i]=4;continue;}longnewWays=((totalWays[i-1]+totalWays[i-2]+totalWays[i-3]+totalWays[i-4])%mod)%mod;totalWays[i]=newWays;}// DP casesBigIntegernewMod=newBigInteger(Integer.toString(mod));BigIntegerexp=newBigInteger(Integer.toString(n));BigIntegerbase2=newBigInteger("2");long[]validWalls=newlong[m+1];long[]invalidWalls=newlong[m+1];validWalls[1]=1;validWalls[2]=base2.modPow(exp,newMod).longValue()-1;invalidWalls[1]=0;invalidWalls[2]=1;for(inti=3;i<=m;i++){BigIntegerbase=newBigInteger(Long.toString(totalWays[i]));longtotalWalls=base.modPow(exp,newMod).longValue();totalDP[i]=totalWalls;longcurrInvalid=0;for(intj=1;j<=i-1;j++){longinvalidUnseen=(validWalls[j]*validWalls[i-j])%mod;longinvalidSeen=(validWalls[j]*invalidWalls[i-j])%mod;longtotalInvalid=(invalidUnseen+invalidSeen)%mod;currInvalid=(currInvalid+totalInvalid)%mod;}invalidWalls[i]=currInvalid;validWalls[i]=(totalWalls-invalidWalls[i]+mod)%mod;}// Last rowreturnvalidWalls[m];}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Lego Blocks
You are viewing a single comment's thread. Return to all comments →
O(m^2) solution. If you're working in Java, the BigInteger class is very useful for efficient modular power operations. Basically, find all the possible permutations of a single row, then, for each wall width, find all the invalid walls and subtract from all possible walls using DP.