LeetCode 2138: Divide a String Into Groups of Size k Solution

Master LeetCode problem 2138 (Divide a String Into Groups of Size k), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2138. Divide a String Into Groups of Size k

Problem Explanation

Explanation:

To solve this problem, we can iterate through the string s in groups of size k and add each group to the result array. If the last group does not have enough characters, we fill it with the given fill character. We keep track of the current starting index for each group and handle the edge case where the last group may not be fully filled.

  • Time complexity: O(n) where n is the length of the input string s.
  • Space complexity: O(n) for the resulting array.

Solution Code

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<String> groupStrings(String s, int k, char fill) {
        List<String> result = new ArrayList<>();
        int start = 0;
        while (start < s.length()) {
            int end = Math.min(start + k, s.length());
            String group = s.substring(start, end);
            if (group.length() < k) {
                group = group + new String(new char[k - group.length()]).replace("\0", String.valueOf(fill));
            }
            result.add(group);
            start += k;
        }
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2138 (Divide a String Into Groups of Size k)?

This page provides optimized solutions for LeetCode problem 2138 (Divide a String Into Groups of Size k) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2138 (Divide a String Into Groups of Size k)?

The time complexity for LeetCode 2138 (Divide a String Into Groups of Size k) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2138 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2138 in Java, C++, or Python.

Back to LeetCode Solutions