File: divide-a-string-into-groups-of-size-k/solution.py

Date: 2026-06-06

Time: 16:26

divide-a-string-into-groups-of-size-k/solution.py

Purpose

This file solves LeetCode 2138 — Divide a String Into Groups of Size k. It takes a string, splits it into consecutive chunks of exactly k characters, and pads the final chunk with a fill character if the string length isn't evenly divisible by k.

Key Components

Solution.divideString(s, k, fill) -> List[str] — The sole method. Takes a string s, group size k, and a single padding character fill. Returns a list of strings each of length k.

Flow

The method works in two steps:

1. Pad: s += fill * ((k - len(s) % k) % k) — appends enough copies of fill to make len(s) a multiple of k. The double-mod (k - len(s) % k) % k computes the deficit: if len(s) is already a multiple of k, the inner mod yields k, and the outer mod collapses that to 0 (no padding). Otherwise it yields exactly the number of fill characters needed.

2. Slice: [s[i:i + k] for i in range(0, len(s), k)] — walks through the padded string in steps of k, producing one substring per step.

Patterns

Dependencies

Invariants

Error Handling

None. The method trusts its inputs match the LeetCode contract (1 <= len(s), 1 <= k, fill is a single lowercase letter). If k is 0, this would raise ZeroDivisionError from the mod, and ValueError from range. No defensive checks are added — standard practice for competitive programming solutions.

Beliefs