Problem solution · Python

ARC140 A — Right String

ARC140 A — Right String: a Python solution using hash-based lookup. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Hash-based lookup
Source
KATO-Hiro AtCoder Solutions
Length
70 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Hash-based lookup

For ARC140 A — Right String, the implementation stores previously seen values or frequencies in a hash table for direct membership and lookup operations.

  1. Decide the key that represents the information needed later.
  2. Update its count or stored state while scanning the input.
  3. Use constant-time expected lookups to detect matches or assemble the result.

Code notes

  • 70 lines of Python from the credited upstream file arc140_a.py.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
  • No explicit loop blocks detected.

Complexity

Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from KATO-Hiro AtCoder Solutions by KATO-Hiro and is used under the CC0-1.0 licence.

Full codeARC140 A — Right String · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def generate_divisors(n: int) -> list[int]:    """    Args:        n: Int of number (greater than 0).     Returns:        List of divisors.        (When n is less than or equal to 2 * 10 ** 5, the number of elements         is at most 160.)     Landau notation: O(√n)     See:    https://qiita.com/LorseKudos/items/9eb560494862c8b4eb56    """     lower_divisors, upper_divisors = [], []    i = 1     while i * i <= n:        if n % i == 0:            lower_divisors.append(i)             if i != n // i:                upper_divisors.append(n // i)         i += 1     return lower_divisors + upper_divisors[::-1]  def main():    import sys    from collections import Counter     input = sys.stdin.readline     n, k = map(int, input().split())    s = input().rstrip()    periods = generate_divisors(n)    ans = 10**18     for period in periods:        candidate = 0         for i in range(period):            j = i            freq = Counter()             while j < n:                freq[s[j]] += 1                j += period             _, count = freq.most_common()[0]            candidate += (n // period) - count         if candidate > k:            continue         ans = min(ans, period)     print(ans)  if __name__ == "__main__":    main() 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗