Skip to content

← leetcode

Divide a String Into Groups of Size k

· Easy

LeetCode problem 2138

Just an implementation question.

Simply iterate through and append each k-sized section to ans. If the last section is shorter than k, then simply fill up the remaining letters with the fill letter.

code

class Solution {
public:
    vector<string> divideString(string s, int k, char fill) {
        vector<string> ans;
        for (int i = 0; i < s.size(); i += k) {
            ans.push_back(s.substr(i, min((int)s.size()-i, k)));
        }

        int n = ans.back().size();
        if (n < k) {
            ans.back().append((k - n), fill);
        }

        return ans;
    }
};

complexity

  • Time: O(n)
  • Space: O(n)

learnings

  • you can do .append((k-n), fill) to append more k-n characters

time taken

  • 4 minutes and 22 seconds