Datasets:

Modalities:
Image
Text
Formats:
parquet
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
hackercup / 2021 /round1 /weak_typing_ch2_sol.md
wjomlex's picture
2021 Problems
d3f4f72 verified
|
raw
history blame
974 Bytes

As in Chapter 1, we should begin by observing that hand switches are required whenever, once "F"s are ignored, an "X" is followed by an "O" or vice versa.

We can iterate through (S) and identify all such pairs of letters (either an "X" followed by an "O", with only "F"s in between, or vice versa). For each such pair, if it involves letters at indices (a) and (b) in (S) (such that (a \lt b)), then it effectively contributes an addition of (1) to the value of (F) for each substring of (S) which includes the entire substring (S_{a..b}) (as each such substring would have a hand switch in between typing the pair's letters). There are (a * (|S| - b + 1)) such substrings, meaning that such a pair contributes an addition of (a * (|S| - b + 1)) to (G(S)). Therefore, we can add all of these products up in a total of (O(N)) time to arrive at the final value of (G(S)).

See David Harmeyer's solution video here.