DDSA Solutions

2138. Divide a String Into Groups of Size k

Time: O(n)
Space: O(n)
Advertisement

Approach

Partition string into ceil(n/k) groups of k, padding last with fill character.

Key Techniques

String

String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.

Simulation

Simulation problems require implementing the described process step by step. Focus on correctly handling edge cases and state transitions. Common in geometry, game problems, and string manipulation. Optimize only if the naive simulation exceeds the time limit.

2138.cs
C#
// Approach: Partition string into ceil(n/k) groups of k, padding last with fill character.
// Time: O(n) Space: O(n)

public class Solution
{
    public string[] DivideString(string input, int partitionSize, char fillCharacter)
    {
        // Determine the length of the input string.
        int inputLength = input.Length;

        // Calculate the required number of partitions.
        int totalPartitions = (inputLength + partitionSize - 1) / partitionSize;

        // Initialize the answer array with the calculated size.
        string[] partitions = new string[totalPartitions];

        // If the input string is not a multiple of partition size, append fill characters to make it so.
        if (inputLength % partitionSize != 0)
            input += new string(fillCharacter, partitionSize - inputLength % partitionSize);

        // Loop through each partition, filling the partitions array with substrings of the correct size.
        for (int i = 0; i < partitions.Length; ++i)
        {
            // Calculate the start and end indices for the substring.
            int start = i * partitionSize;
            int end = (i + 1) * partitionSize;

            // Extract the substring for the current partition and assign it to the partitions array.
            partitions[i] = input.Substring(start, partitionSize);
        }

        // Return the final array of partitions.
        return partitions;
    }
}
Advertisement
Was this solution helpful?