if(sum < 0) { sum = sum + mod; } I didn't get this part. However -ve value is also possible then if we add 10^9+7 it will become +ve which is wrong. Please clarify this.