Divide a String Into Groups of Size k Problem
#2138
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2138.
A string s can be partitioned into groups of size k using the following procedure:
- The first group consists of the first
kcharacters of the string, the second group consists of the nextkcharacters of the string, and so on. Each element can be a part of exactly one group. - For the last group, if the string does not have
kcharacters remaining, a characterfillis 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 <= 100sconsists of lowercase English letters only.1 <= k <= 100fillis a lowercase English letter.
Solution
Approach: Simulation
Cut the string into pieces of k characters from the left. If the last piece is shorter than k, pad it with fill up to length k.
Time O(n), space O(n), where n is the length of s.
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)]