M71CNTAB - Editorial

PROBLEM LINK:

Practice

Contest

Author: nmalviya1929

Tester: manjunath1996

Editorialist: nmalviya1929

DIFFICULTY:

SIMPLE

PREREQUISITES:

None

PROBLEM:

Given a string s consisting of a and b. Find number of subsequence “ab” in s.

QUICK EXPLANATION:

This problem can be simplified as for each b, find the total number of a that precedes it. Answer is the summation of all the values.

EXPLANATION:

Question can be simplified as for a particular bi ,we have to find all the subsequence “ajbi” where 0<=j< i .This value is equal to number of a’s preceding b.Answer is summation of all this values.

To calculate number of a’s that precede each b, we will keep a variable count that will keep track of number of a’s encountered so far while traversing string from left to right.
While traversing string from left to right , whenever an ‘a’ is encountered, we will increment count variable and wheneber ‘b’ is encountered we will increment answer by count.

AUTHOR’S AND TESTER’S SOLUTIONS:

Author’s solution can be found here.

Tester’s solution can be found here.

1 Like