Engineering platform~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-696strings
A build system runs a health check every minute. The result is 1 for a pass and 0 for a fail, so a day is a string of ones and zeros.
A flap is a stretch of some number k of equal results, followed at once by k of the opposite result. For example 0011 is a flap with k = 2, and 10 is a flap with k = 1. Your team lead wants to count the flaps.
Write count_flaps(checks).
Input: checks = "00110011"
Output: 6The string 00110011 has 6 flaps. The runs are 00, 11, 00 and 11. Every pair of neighbouring runs gives as many flaps as the shorter run is long.
| Neighbouring runs | Shorter run | Flaps |
|---|---|---|
00 and 11 |
2 | 0011, 01 |
11 and 00 |
2 | 1100, 10 |
00 and 11 |
2 | 0011, 01 |
The answer is 6.
Input: checks = "10101"
Output: 4Every run has length 1. The flaps are 10, 01, 10 and 01: four of them.
Input: checks = "0000"
Output: 0There is only one run, so the symbol never changes, and no flap exists.
1 ≤ length of checks ≤ 10^5checks has only the characters 0 and 1A string of 100,000 symbols has about 5 x 10^9 stretches, and checking one means reading it. That is far too slow.
The answer depends only on the lengths of the runs and not on the positions inside them. One pass over the string can find the run lengths.