- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 64 lines of Python from the credited upstream file abc398_f.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3import typing4 5 678def z_algorithm(s: typing.Union[str, typing.List[int]]) -> typing.List[int]:9 """10 Reference:11 D. Gusfield,12 Algorithms on Strings, Trees, and Sequences: Computer Science and13 Computational Biology14 """15 16 if isinstance(s, str):17 s = [ord(c) for c in s]18 19 n = len(s)20 21 if n == 0:22 return []23 24 z = [0] * n25 j = 026 27 for i in range(1, n):28 z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j])29 30 while i + z[i] < n and s[z[i]] == s[i + z[i]]:31 z[i] += 132 33 if j + z[j] < i + z[i]:34 j = i35 36 z[0] = n37 38 return z39 40 41def main():42 import sys43 44 input = sys.stdin.readline45 46 s = input().rstrip()47 n = len(s)48 t = s[::-1] + s49 z = z_algorithm(t)50 51 for i in range(n):52 if z[n + i] != n - i:53 continue54 55 ans = s56 ans += t[n - i : n]57 print(ans)58 59 break60 61 62if __name__ == "__main__":63 main()64