- 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
- 74 lines of Go from the credited upstream file 2069D.go.
- The implementation keeps its working state in language-native values and containers.
- 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.
1package main2 3import (4 . "fmt"5 "io"6)7 89func cf2069D(in io.Reader, out io.Writer) {10 T, s := 0, ""11 for Fscan(in, &T); T > 0; T-- {12 Fscan(in, &s)13 n := len(s)14 l := 015 for l < n/2 && s[l] == s[n-1-l] {16 l++17 }18 if l == n/2 {19 Fprintln(out, 0)20 continue21 }22 r := n/2 - 123 for s[r] == s[n-1-r] {24 r--25 }26 27 var tot, cnt [26]int28 for i := l; i <= r; i++ {29 cnt[s[i]-'a']++30 tot[s[i]-'a']++31 tot[s[n-1-i]-'a']++32 }33 bal := true34 for i, c := range cnt {35 if c*2 != tot[i] {36 bal = false37 break38 }39 }40 if bal {41 Fprintln(out, r-l+1)42 continue43 }44 45 clear(tot[:])46 for _, v := range s[l : n-l] {47 tot[v-'a']++48 }49 50 clear(cnt[:])51 rr := n - 1 - l52 for ; ; rr-- {53 v := s[rr] - 'a'54 cnt[v]++55 if cnt[v] > tot[v]/2 {56 break57 }58 }59 60 clear(cnt[:])61 ll := l62 for ; ; ll++ {63 v := s[ll] - 'a'64 cnt[v]++65 if cnt[v] > tot[v]/2 {66 break67 }68 }69 Fprintln(out, min(rr-l+1, n-l-ll))70 }71}72 7374