Count Subsequences - DP. Passing sample cases. But 4 Test cases are failing

import java.io.;
import java.util.
;

public class Main
{
public static void main(String [] args) throws Exception
{
Scanner scn = new Scanner(System.in);

	int t = scn.nextInt();

	scn.nextLine();

	while(t-- != 0)
	{
		String s = scn.nextLine();
		int n = s.length();

		//each index correspons to each character of the string
		//this array stores the count of distinct subsequences
		//using 1st character to current character of the string.
		long [] dp = new long[n + 1];

		//empty subsequence will be stored in 0th index
		//thus, dp size is s.length + 1
		//count of 1st empty subsequence = 1 stored in dp[0].
		dp[0] = 1;

		//stores the characters covered so far with the index
		//at which they last occured.
		HashMap <Character , Integer> lastOccurrence = new HashMap <> ();

		for(int i = 1; i<=n; i++)
		{
			//don't add the current character into previous set of characters
			//plus
			// add the current character into the previous set of characters.
			//gives the total possible subsequences till the current character.
			//which may not be distinct
			dp[i] = (dp[i-1]*2)%1000000007;

			char cc = s.charAt(i-1);

			//if the character already occurred before.
			if(lastOccurrence.containsKey(cc))
			{
				int prevIndex = lastOccurrence.get(cc);

				//subtract the no. of subsequence just before
				//the last occurrence of the character.
				dp[i] = (dp[i] - dp[prevIndex - 1])%1000000007;
			}

			//update the last occurrence of the character.
			lastOccurrence.put(cc,i);

		}

		System.out.println(dp[n]%1000000007);
	}
}

}

Code is fine
Issue is with modulo
When taking modulo
Always do
( ( X % M ) + M ) % M
Line 51 might store negative value in dp[i]
Final ans may turn out to be negative
here s your corrected code: https://ide.codingblocks.com/s/357404

Ok Mam, thanks. Now, it is working.

Mam How can we solve the same problem with BitMasking as it is given in the bitMasking section?

this problem is a good dp problem again a combinatorial optimization problem. Think it with dp, dp is the best approach to this problem.

There should be a reason to apply a specific paradigm. Rather than going for bitmasking go for dp, because you have to find out count of distinct subs. And while finding count, don’t generate all the subsequences. In dp don’t generate side effect outputs. Here we don’t have to generate all possible candidates of outputs so go with dp rather than bitmasking