Problem 2138

Abstract / Summary

Divide a string into consecutive groups of size k and return the groups as a list of strings.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2138.py

class Solution:
    def divideString(self, s: str, k: int, fill: str) -> List[str]:
        for i in range(0, len(s), k):
            group = s[i : i + k]
            if len(group) < k:
                group += fill * (k - len(group))
            yield group
7 lines | 266 bytes | submitted January 28, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 77% (200k+ submissions).

Typical patterns to solve this problem:
  • Simulation
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a generator method divideString that partitions an input string s into fixed-length substrings of size k. When the final segment is shorter than k, it is padded on the right with a repeated fill character fill until the required length is reached. The method yields each segment one at a time, allowing the caller to iterate lazily over the results.

Iteration Over the Input

The core of the algorithm is a for loop that steps through the string in increments of k. By using the built-in range with a step argument, the loop computes the start index of each block without creating intermediate collections.

for i in range(0, len(s), k):

This approach ensures that the loop visits every k-character window exactly once, regardless of the total length of s.

Extraction of a Candidate Group

Within each iteration, a slice operation extracts the substring beginning at the current index i and extending up to i + k. Python slicing gracefully handles cases where the end index exceeds the string length, returning a shorter substring without raising an error.

group = s[i : i + k]

The slice therefore yields either a full-length segment or the residual characters at the end of the string.

Padding the Final Segment

When the extracted group is shorter than the desired length k, the code computes the deficit and appends the appropriate number of fill characters. The multiplication of the fill character by the deficit creates the exact padding needed in a single operation.

if len(group) < k:
    group += fill * (k - len(group))

This conditional block handles the edge case where the original string length is not a multiple of k. It also correctly deals with an empty input string, producing a single padded segment if k is greater than zero.

Yielding Results Lazily

Instead of accumulating all groups in a list, the method uses the yield statement to produce each segment on demand. This generator pattern conserves memory because only one segment resides in memory at any moment during iteration.

yield group

The lazy evaluation also enables the caller to stop processing early without incurring the cost of generating the remaining groups.

Edge Cases Addressed

The implementation naturally accommodates several boundary conditions:

  • When s is empty, the loop body never executes, resulting in no output, which aligns with the expectation of dividing an empty string.
  • If k equals the length of s, a single iteration yields the original string unchanged.
  • When k exceeds the length of s, the first (and only) slice returns the whole string, and the padding logic expands it to exactly k characters.
  • The fill character can be any single-character string; multiplication replicates it correctly even if it is a whitespace or numeric character.

Performance Optimizations Observed

The code leverages Python’s efficient slice operation and string multiplication, both of which are implemented in C and run at native speed. By iterating with a step size of k, the loop avoids unnecessary index calculations inside the body. The use of a generator eliminates the overhead of building an intermediate list, reducing both memory footprint and allocation time for large inputs. The conditional padding is executed only for the final segment, minimizing extra work for the majority of iterations.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long, silly string of colorful beads that you want to put into small boxes. Every box has space for exactly the same amount of beads. The code looks at the long string and decides how to chop it up into these little groups. First, it walks along the beads, grabbing a handful at a time. If the last box is not quite full because there are not enough beads left to fill it to the brim, the code grabs extra special filler beads to top it off so that every box is perfectly full. Each time a box is ready, it gets set aside so someone can use it.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.15 | σ = 1.43

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
25 links | 14 authors | 8 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   January 28, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality