Skip to content

2138. Divide a String Into Groups of Size k 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  vector<string> divideString(string s, int k, char fill) {
    vector<string> ans;

    for (int i = 0; i < s.length(); i += k)
      ans.push_back(i + k > s.length()
                        ? s.substr(i) + string(i + k - s.length(), fill)
                        : s.substr(i, k));

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public String[] divideString(String s, int k, char fill) {
    String[] ans = new String[(s.length() + k - 1) / k];

    for (int i = 0, j = 0; i < s.length(); i += k)
      ans[j++] = i + k > s.length()
                     ? s.substring(i) + String.valueOf(fill).repeat(i + k - s.length())
                     : s.substring(i, i + k);

    return ans;
  }
}
1
2
3
4
5
6
7
class Solution:
  def divideString(self, s: str, k: int, fill: str) -> list[str]:
    return [
        s[i:] + fill * (i + k - len(s)) if i + k > len(s)
        else s[i:i + k]
        for i in range(0, len(s), k)
    ]