Problem · String

Count Substrings

Learn this problem
MediumSalesforceOA
See Salesforce hiring insights

Problem statement

Count substrings that satisfy the following two conditions:

  1. Count of 1s and count of 0s is equal.
  2. Should be a block of 0s followed by a block of 1s or vice versa.

Examples of such substrings are "0011", "01", "10", "1100".

You can count repetitions, for example, "10101" has 4 such substrings: "10", "01", "10", "01".

Function

countSubstrings(s: String) → int

Complete the function countSubstrings in the editor.

countSubstrings has the following parameter:

  1. String s: the binary string to be checked

Returns

int: the number of substrings that satisfy the conditions

Examples

Example 1

s = "10101"return = 4
The string "10101" contains the following substrings that satisfy the conditions:
  • "10": A block of 1 followed by a block of 0.
  • "01": A block of 0 followed by a block of 1.
  • "10": Another block of 1 followed by a block of 0.
  • "01": Another block of 0 followed by a block of 1.
There are a total of 4 such substrings, so the answer is 4.

More Salesforce problems

drafts saved locally
public int countSubstrings(String s) {
  // write your code here
}
s"10101"
expected4
checking account