InternDoor

Pieces with as many 0s as 1s

Mediumstrings · prefix sums · hashing

Reported in interviews at (where)

s is made of the characters 0 and 1. Count its substrings (runs of characters next to each other) that hold exactly as many 0s as 1s, in any order.

Substrings at different positions count separately, even when they read the same. The count can be large, so it is returned as a long.

Example 1
Input
s = "0110"
Output
3

"01" at the start, "10" at the end, and the whole string, which has two of each.

Example 2
Input
s = "0101"
Output
4

Three pieces of length 2 ("01", "10", "01") and the whole string.

Example 3
Input
s = "000"
Output
0

No piece has a 1.

Limits

  • 1 <= s.length <= 100000
  • s holds only 0 and 1

Hints

Hint 1

Keep a running balance: add 1 for each 1 and subtract 1 for each 0. A piece has as many 0s as 1s exactly when the balance is the same just before it starts and just after it ends.

Hint 2

So count, for every balance value, how many prefixes reach it. Each pair of prefixes with the same balance is one piece. Start with the empty prefix at balance 0.

Where this was reported

Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.

Run your code to check it on the examples. Submit runs every hidden test.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.