Skip to main content

Divide a String Into Groups of Size k - Solution & Explanation

EasyStringSimulation12 min readAsked at: Google, Canonical, Bloomberg
Practice this problem

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 character can be a part of exactly one group.
  • For the last group, if the string does not have k characters remaining, a character fill is used to complete the group.

Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s.

Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.

 

Example 1:

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".

Example 2:

Input: s = "abcdefghij", k = 3, fill = "x"
Output: ["abc","def","ghi","jxx"]
Explanation:
Similar to the previous example, we are forming the first three groups "abc", "def", and "ghi".
For the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.
Thus, the 4 groups formed are "abc", "def", "ghi", and "jxx".

 

Constraints:

  • 1 <= s.length <= 100
  • s consists of lowercase English letters only.
  • 1 <= k <= 100
  • fill is a lowercase English letter.

Approach Overview

Problem Overview: You are given a string s, an integer k, and a fill character. Split the string into consecutive groups of length k. If the final group has fewer than k characters, pad it with the fill character until the group size becomes k.

The task is mostly a straightforward string manipulation problem. You iterate over the string in fixed-size chunks, build substrings, and ensure the final chunk has exactly k characters.

Approach 1: Using Loop and Substring (O(n) time, O(n) space)

Iterate through the string with a step size of k. At each step, extract a substring from index i to i + k. If the substring length is already k, add it directly to the result list. If the substring is shorter than k, append the fill character repeatedly until its length becomes k. This approach relies on basic substring extraction and array/list storage.

The key insight is that you never need complex data structures. Each character in the string is processed exactly once, which keeps the time complexity linear. The algorithm fits well into a simple simulation pattern where you emulate the grouping process step by step.

Approach 2: List Comprehension with Padding (O(n) time, O(n) space)

This variation is more concise in languages like Python or JavaScript. First compute all substrings of length k using slicing inside a list comprehension or array mapping step. For the last group, check if its length is smaller than k. If so, append the required number of fill characters using string multiplication or repeat operations.

The logic remains identical to the loop-based approach but compresses the iteration and substring creation into a single expression. The padding step ensures the last group always meets the size requirement. Under the hood, you still iterate over the string once and build the output list.

Both solutions operate in O(n) time because each character of the string is visited at most once. The extra space complexity is also O(n) because the resulting list of groups stores all characters again.

Recommended for interviews: The loop and substring approach is the most expected solution. It clearly demonstrates control over indexing, substring extraction, and edge case handling for the final group. The list comprehension version is shorter but may hide the logic during interviews. Start with the explicit loop to show clarity, then mention the concise version if the interviewer asks about code optimization.

Approach 1: Using Loop and Substring

This approach involves iterating through the string in increments of k and forming each group by taking k characters. If the number of characters left is less than k and a fill character is required, we append the fill character accordingly to complete the group.

The C code utilizes the printf function to extract substrings of size k from the input string s. It uses the integer division method to determine how many full groups are required. For the remainder of the string that does not fill an entire group, the fill character is appended until the group is complete.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the string s.
Space Complexity: O(1), as no extra space other than a few variables is used.

Try this approach in the editor →

Approach 2: Using List Comprehension and Padding

This approach builds on modern language features such as list comprehensions and string formatting to achieve a succinct solution. By leveraging these tools, we can split the string into fixed-sized parts and adjust any part that doesn't meet the required size through padding.

In this Python solution, a list comprehension generates each group. The slice is padded with fill charaacters, but only up to a length of k, to ensure that every group is the correct size.

Code

Python

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the string s.
Space Complexity: O(n/k), due to list storage.

Try this approach in the editor →

Approach 3: Simulation

We can directly simulate the process described in the problem statement, dividing the string s into groups of length k. For the last group, if it contains fewer than k characters, we use the character fill to pad it.

The time complexity is O(n), and the space complexity is O(n), where n is the length of the string s.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Using Loop and Substring

Time Complexity: O(n), where n is the length of the string s.
Space Complexity: O(1), as no extra space other than a few variables is used.

Using List Comprehension and Padding

Time Complexity: O(n), where n is the length of the string s.
Space Complexity: O(n/k), due to list storage.

Simulation—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Loop with Substring ExtractionO(n)O(n)Best general solution. Clear indexing logic and easy to implement in any language.
List Comprehension with PaddingO(n)O(n)Useful in Python or JavaScript for concise code when readability is still acceptable.

Video Solution

Divide a String Into Groups of Size k | Easy | Leetcode 2138 | codestorywithMIK • codestorywithMIK • 4,217 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Divide a String Into Groups of Size k easy or hard?
The problem is categorized as Easy on LeetCode. It mainly tests basic string manipulation, indexing, and edge-case handling when the final group is shorter than k.
Divide a String Into Groups of Size k Python/Java solution
In Python, you can iterate with range(0, len(s), k) and slice the string using s[i:i+k], then pad the final group with the fill character. In Java, use substring(i, Math.min(i + k, s.length())) and append fill characters using a StringBuilder if the group is shorter than k.
How to solve Divide a String Into Groups of Size k in O(n)?
Traverse the string using a loop that increments by k each step. Extract substrings using slicing or substring operations. If the final group length is less than k, append the fill character until it reaches size k. Since each character is processed once, the total runtime remains O(n).
What is the best approach for Divide a String Into Groups of Size k?
The most practical approach is iterating through the string in steps of k and extracting substrings. If the final substring has fewer than k characters, pad it with the fill character. This simulation approach runs in O(n) time and is easy to implement in all major languages.
Is Divide a String Into Groups of Size k asked at Google/Amazon/Meta?
Problems involving string chunking and padding frequently appear in interviews at companies like Amazon, Google, and Meta. While this exact problem may vary, similar string manipulation and simulation questions are common screening tasks.
What data structure is used in Divide a String Into Groups of Size k?
The solution primarily uses strings and a dynamic array or list to store the resulting groups. No advanced data structures are required, which makes it a straightforward string simulation problem.
What is the time complexity of Divide a String Into Groups of Size k?
The time complexity is O(n), where n is the length of the string. Each character is processed exactly once while forming groups. The space complexity is also O(n) because the output list stores all grouped characters.

Ready to solve this problem?

Practice Divide a String Into Groups of Size k with our built-in code editor and test cases.

Practice on FleetCode