EasyNo. 2243
Calculate Digit Sum of a String — LeetCode 2243 Python Solution
- Pattern
- Hash Map
- Topics
- String, Simulation
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a string s consisting of digits and an integer k. A round can be completed if the length of s is greater than k.
Example
- Input
- s = "11111222223", k = 3
- Output
- "135"
- Explanation
- - For the first round, we divide s into groups of size 3: "111", "112", "222", and "23".
Python solution
class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
t = []
n = len(s)
for i in range(0, n, k):
x = 0
for j in range(i, min(i + k, n)):
x += int(s[j])
t.append(str(x))
s = "".join(t)
return sComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2243. Calculate Digit Sum of a String is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0068 | Text Justification | Hard |
| 0657 | Robot Return to Origin | Easy |
| 1324 | Print Words Vertically | Medium |
| 1545 | Find Kth Bit in Nth Binary String | Medium |
| 1945 | Sum of Digits of String After Convert | Easy |
| 2011 | Final Value of Variable After Performing Operations | Easy |
Frequently asked questions
- How hard is LeetCode 2243. Calculate Digit Sum of a String?
LeetCode 2243. Calculate Digit Sum of a String is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2243. Calculate Digit Sum of a String?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2243. Calculate Digit Sum of a String?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2243. Calculate Digit Sum of a String cover?
LeetCode 2243. Calculate Digit Sum of a String is tagged String and Simulation on LeetCode.