We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Divide a String Into Groups of Size k

Number: 2260

Difficulty: Easy

Paid? No

Companies: Canonical


Problem Description

Given a string s, an integer k, and a character fill, partition s into groups of k characters. For each complete group of k characters, use them directly. For the last group, if less than k characters remain, pad the group with the fill character so that its length becomes k. Return the list of groups.


Key Insights

  • Process the string in chunks of size k.
  • For each chunk of exactly k characters, add it as is.
  • For the last chunk, if its size is less than k, append the fill character until the chunk reaches the required length.
  • The concatenation of the groups without the fill characters (from the last group) should yield the original string.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string, since we iterate through it once. Space Complexity: O(n), as we store the resulting groups which collectively have a length proportional to the original string (plus possible extra characters for the last group).


Solution

The solution involves iterating through the input string s in steps of size k. For each step, extract a substring of length k. If the substring length is less than k, pad it with the fill character until it reaches a length of k. We use a simple loop to extract these groups and check the last group separately for potential padding. Data structures used include a list (or array) to store the resulting groups, and standard string slicing and concatenation for creating each group.


Code Solutions

# Define the function to divide the string into groups of size k
def divideString(s, k, fill):
    # Initialize the list to store the groups
    groups = []
    # Iterate through string in steps of k
    for i in range(0, len(s), k):
        # Extract the current group substring of length k
        group = s[i:i+k]
        # If the group is shorter than k, pad it with the fill character
        if len(group) < k:
            group += fill * (k - len(group))
        # Append the valid group to the groups list
        groups.append(group)
    # Return the list of groups
    return groups

# Example usage:
print(divideString("abcdefghij", 3, "x"))  # Output: ['abc', 'def', 'ghi', 'jxx']
← Back to All Questions