Leetcode 2138: Divide a String Into Groups of Size k

Pierre-Marie Poitevin
2 min readJan 17, 2022

In this problem, we divide a String into a list of substrings of size k. In the last String is not of size k, we complete the string with a fill character until the string is of size k.

Example:
s = "abcdef", k = 4, fill = 'x'
Return: ["abcd", "efxx"]
  • First, we want all the substrings of size k by using the function substring in a loop. In the loop we will keep track of an index currIndex starting at 0 and incremented of k after each iteration.
  • The loop stops when currIndex + k > n, with n the size of the input String.
  • When the loop is done, we need to find out if the last string is incomplete, in which case we need to fill the string using fill.
  • If the current index currIndex is less than n, then we need to create a filler string by adding the fill character k — (n — currIndex) times, then adding it to the remaining String.
  • We create a function repeatChar for readability, that returns a String consisting of one char fill repeated repeat times.
  • In the algorithm, we add all the Strings to a List (for instance ArrayList), that we convert to an array at the end to fit with the problem output.

In summary:

Main algorithm ideas

This is the code I obtained in Java:

class Solution {

public String repeatChar(char fill, int repeat) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < repeat; i++) {
sb.append(fill);
}
return sb.toString();
}

public String[] divideString(String s, int k, char fill) {
List<String> res = new ArrayList<>();
int currIndex = 0;
int n = s.length();
while (currIndex + k < n) {
res.add(s.substring(currIndex, currIndex + k));
currIndex += k;
}
if (currIndex < n) {
int repeat = k - (n - currIndex);
String rest = repeatChar(fill, repeat);
String last = s.substring(currIndex, n) + rest;
res.add(last);
}
return res.toArray(new String[res.size()]);
}
}

Happy coding!

--

--