Calculate Digit Sum of a String — LeetCode 2243 Python Solution
EasyStringSimulation
- Problem
- #2243
- Pattern
- Hash Map
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
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.