Skip to content

Commit 991a4a1

Browse files
committed
feat: 2138
1 parent ac22d37 commit 991a4a1

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# 2138. Divide a String Into Groups of Size k
2+
3+
## Intuition
4+
5+
The problem requires dividing a string into groups of size k. If the last group has fewer characters than k, we need to fill it with the given fill character until it reaches size k. This suggests using a loop to process the string in chunks of k characters.
6+
7+
## Approach
8+
9+
1. Create an empty slice to store the resulting strings
10+
2. Iterate through the string with steps of k characters
11+
3. For each iteration:
12+
- If there are at least k characters remaining, take a substring of k characters
13+
- If there are fewer than k characters remaining:
14+
- Take the remaining characters
15+
- Fill the rest with the given fill character until reaching length k
16+
4. Return the resulting slice of strings
17+
18+
## Complexity
19+
20+
- Time complexity: O(n)
21+
- Space complexity: O(n)
22+
23+
## Keywords
24+
25+
- String Manipulation
26+
- String Padding
27+
28+
## Code
29+
30+
```go
31+
func divideString(s string, k int, fill byte) []string {
32+
ret := make([]string, 0)
33+
for i := 0; i < len(s); i += k {
34+
if i + k < len(s) {
35+
ret = append(ret, string(s[i: i + k]))
36+
} else {
37+
ret = append(ret, string(s[i:]))
38+
for j := len(ret[len(ret) - 1]); j < k; j += 1 {
39+
ret[len(ret) - 1] += string(fill)
40+
}
41+
}
42+
}
43+
return ret
44+
}
45+
```

docs/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777
| 1395 | Count Number of Trams | [go](Medium/1395%20Count%20Number%20of%20Teams.md) | M |
7878
| 2016 | Maximum Difference Between Increasing Elements | [go](Easy/2016%20Maximum%20Difference%20Between%20Increasing%20Elements.md) | E |
7979
| 2071 | Maximum Number of Tasks You Can Assign | [go](Hard/2071%20Maximum%20Number%20of%20Tasks%20You%20Can%20Assign.md) | H |
80+
| 2138 | Divide a String Into Groups of Size k | [go](Easy/2138%20Divide%20a%20String%20Into%20Groups%20of%20Size%20k.md) | E |
8081
| 2294 | Partition Array Such That Maximum Difference Is K | [go](Medium/2294%20Partition%20Array%20Such%20That%20Maximum%20Difference%20Is%20K.md) | M |
8182
| 2366 | Mimimum Replacements to Sort the Array | [go](Hard/2366%20Minimum%20Replacements%20to%20Sort%20the%20Array.md) | H |
8283
| 2392 | Build A Matrix with Conditions | [go](Hard/2392%20Build%20A%20Matrix%20With%20Conditions.md) | H |

0 commit comments

Comments
 (0)