#2138

Divide a String Into Groups of Size k

Easy
StringSimulationString ManipulationArray Partitioning
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach calculates how many complete groups can be formed and handles the last group efficiently by checking the remaining characters in one pass.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty list to store the groups.
  2. 2Step 2: Calculate the number of complete groups using integer division of the string length by k.
  3. 3Step 3: Loop through the number of complete groups, appending each group of size k to the list.
  4. 4Step 4: For the last group, check if there are remaining characters. If not enough, fill with the fill character.
  5. 5Step 5: Return the list of groups.
solution.py9 lines
1def divideString(s, k, fill):
2    groups = []
3    n = len(s)
4    complete_groups = n // k
5    for i in range(complete_groups):
6        groups.append(s[i*k:(i+1)*k])
7    last_group = s[complete_groups*k:] + fill * (k - len(s[complete_groups*k:]))
8    groups.append(last_group)
9    return groups

Complexity note: The time complexity is O(n) because we traverse the string a constant number of times, and the space complexity is O(n) due to storing the result in a list.

  • 1Understanding how to handle the last group is crucial for solving this problem.
  • 2Efficiently calculating the number of complete groups can save time and simplify the code.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.