2138. Divide a String Into Groups of Size k
UnknownView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Divide a String Into Groups of Size k (Unknown) asks you to solve a structured algorithmic task. This is a common String / Simulation pattern in coding interviews. Partition string into ceil(n/k) groups of k, padding last with fill character.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Partition string into ceil(n/k) groups of k, padding last with fill character.
Related patterns: String, Simulation
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;
}
}Was this solution helpful?
Related Problems
- 68. Text Justification(Hard)
- 592. Fraction Addition and Subtraction(Unknown)
- 657. Robot Return to Origin(Unknown)
- 838. Push Dominoes(Medium)
- 1545. Find Kth Bit in Nth Binary String(Easy)
- 1598. Crawler Log Folder(Easy)