DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord account linking.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Gugugaga

Back to problem

Editorial

Scan the string from left to right. At the current position, choose the longest given word that matches. Increment its count and advance by its length.

Specifically, test gugugaga, guguga, gugaga, and guga in that order, and choose the first match. The two words of equal length may be checked in either order. Since the input is a concatenation of the four words, at least one word can always be found.

Longer words must be considered first because guga is a prefix of gugaga, and guguga is a prefix of gugugaga. Choosing the shorter word first would leave ga to be incorrectly treated as the start of the next word.

There are only four words, each of length at most 888, so finding the next word takes constant time. The time complexity is therefore O(∣S∣)O(|S|)O(∣S∣). Storing the input string uses O(∣S∣)O(|S|)O(∣S∣) space, while the four counters and the current position require O(1)O(1)O(1) additional space.

Proof

Let WWW be the actual first word in the unprocessed part of the string. Since WWW matches at the current position, the longest matching word VVV chosen by the algorithm cannot be shorter than WWW.

If VVV were longer than WW, then would be a proper prefix of . Among the given words, this happens only in the following two cases:

Solution written by GPT6

W
WWW
VVV
  • gugaga is guga followed by ga.
  • gugugaga is guguga followed by ga.

Thus, incorrectly choosing a longer word would require the two characters immediately after the actual word WWW to be ga. If WWW is the last word, there are no characters after it. Otherwise, the next word starts with gu. Neither case allows ga to follow, so V=WV=WV=W.

After removing this correctly identified word, the remaining string is again a concatenation of the same four words. Repeating the argument proves that every word is identified correctly, so all four counts are correct. It also shows that the decomposition into words is unique.