Divide a String Into Groups of Size k – Java Solution

Language Options

C++ Solution |
Python Solution

Code Solution


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;
  }
}

Problem Description

You have a string, and you want to divide it into groups of size k. If the last group is smaller than k, you need to fill it up with a specified character. This is similar to trying to fit an oversized winter coat into a tiny suitcase; you might have to get creative!

Approach Explanation

The provided code takes a string s, a group size k, and a character fill. It creates an array to hold the resulting groups. The loop iterates through the string in chunks of size k. If the last chunk is smaller than k, it fills the remaining space with the fill character.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the length of the string.
Space Complexity O(n/k), which is the number of groups created.

Real-World Example

Imagine you’re organizing a party and you have a bunch of balloons. You want to group them into bunches of 5. If you have 12 balloons, you’ll have two groups of 5 and one group of 2. But wait! You don’t want that last group to look lonely, so you add 3 more balloons (or maybe just some confetti) to make it look festive. That’s exactly what this problem is about!

Similar Problems

If you enjoyed this problem, you might also like these: