Leetcode #2138: Divide a String Into Groups of Size k
In this guide, we solve Leetcode #2138 Divide a String Into Groups of Size k in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
A string s can be partitioned into groups of size k using the following procedure: The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each element can be a part of exactly one group.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: String, Simulation
Intuition
We need to scan characters while tracking positions or counts.
A simple state machine keeps the logic precise.
Approach
Iterate through the string once and update the state for each character.
Use a map or array if you need fast lookups.
Steps:
- Iterate through characters.
- Maintain necessary state.
- Build or validate the output.
Example
Input: s = "abcdefghi", k = 3, fill = "x"
Output: ["abc","def","ghi"]
Explanation:
The first 3 characters "abc" form the first group.
The next 3 characters "def" form the second group.
The last 3 characters "ghi" form the third group.
Since all groups can be completely filled by characters from the string, we do not need to use fill.
Thus, the groups formed are "abc", "def", and "ghi".
Python Solution
class Solution:
def divideString(self, s: str, k: int, fill: str) -> List[str]:
return [s[i : i + k].ljust(k, fill) for i in range(0, len(s), k)]
Complexity
The time complexity is , and the space complexity is , where is the length of the string . The space complexity is , where is the length of the string .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.