- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 88 lines of Python from the credited upstream file abc401_d.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3from typing import List4 5 6def run_length_encoding(iterable: list) -> List[list]:7 """8 Args:9 iterable: A list of numbers or strings.10 11 Returns:12 A list containing consecutive characters and their count.13 14 See:15 https:qiita.com/DaikiSuyama/items/07e237b7372e7c7b343216 """17 18 from itertools import groupby19 20 results = [[key, len(list(group))] for key, group in groupby(iterable)]21 22 return results23 24 25def main():26 import sys27 28 input = sys.stdin.readline29 30 n, k = map(int, input().split())31 s = list(input().rstrip())32 33 34 for i, si in enumerate(s):35 if si == "o":36 if i - 1 >= 0:37 s[i - 1] = "."38 if i + 1 < n:39 s[i + 1] = "."40 41 42 43 remain = k - s.count("o")44 45 46 results = run_length_encoding(s)47 total = 048 ps = list()49 50 for key, count in results:51 if key == "?":52 ps.append((total, total + count)) 53 54 total += count55 56 candidate_max = 057 58 for left, right in ps:59 candidate_max += (right - left + 1) 260 61 62 63 if remain == 0:64 for i, si in enumerate(s):65 if si == "?":66 s[i] = "."67 68 69 elif remain == candidate_max:70 for left, right in ps:71 if (right - left) % 2 == 0:72 continue73 74 for i in range(right - left):75 if i % 2 == 0:76 s[left + i] = "o"77 else:78 s[left + i] = "."79 80 else:81 pass82 83 print("".join(s))84 85 86if __name__ == "__main__":87 main()88