algoadvance

Leetcode 2138. Divide a String Into Groups of Size k

Problem Statement

You are given a string s of length n and an integer k. You need to divide the string into groups of size k. Each group should be a substring of s. You should also ensure that the last group is the same size as all the other groups or longer. If the last group of the string is shorter than k` characters, pad additional characters to ensure all groups are of the same length.

For instance, if the last group is shorter than k characters, fill the remaining positions with the character '*'.

Clarifying Questions

  1. Can the input string s be empty?
  2. What characters should we use for padding in the last group? (Assuming ‘*’ based on problem description)
  3. Can k be larger than the length of the string s?

Assuming that k will always be a positive integer and the padding character is '*'.

Strategy

  1. Initialize an empty list to store the resulting groups.
  2. Iterate through the string in steps of size k.
  3. Slice the substring of size k from the current starting index and add it to the list.
  4. Check if the length of the current substring is less than k. If so, pad it with ' * ' to make its length equal to k.
  5. Repeat until all slices are processed.
  6. Return the list of groups.

Code

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

public class Solution {
    public List<String> divideString(String s, int k, char fill) {
        List<String> result = new ArrayList<>();
        int n = s.length();

        for (int i = 0; i < n; i += k) {
            StringBuilder group = new StringBuilder();
            int remainingLength = (i + k <= n) ? k : n - i;
            group.append(s, i, i + remainingLength);

            while (group.length() < k) {
                group.append(fill);
            }

            result.add(group.toString());
        }

        return result;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.divideString("abcdefghi", 3, '*')); // Output: [abc, def, ghi]
        System.out.println(sol.divideString("abcdefghij", 3, '*')); // Output: [abc, def, ghi, j**]
    }
}

Time Complexity

This approach ensures that each group is correctly padded and all groups are of size k or extended to size k if the last group is shorter than k characters.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI