question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sum-of-floored-pairs | Prefix array sum of frequencies | prefix-array-sum-of-frequencies-by-manav-u0ag | \nclass Solution {\n long long mod = 1e9 + 7;\npublic:\n int sumOfFlooredPairs(vector<int>& nums) {\n vector<long long> freq(1e5 + 1, 0);\n | manav1811kumar | NORMAL | 2021-09-09T18:31:21.990839+00:00 | 2021-09-09T18:31:21.990871+00:00 | 244 | false | ```\nclass Solution {\n long long mod = 1e9 + 7;\npublic:\n int sumOfFlooredPairs(vector<int>& nums) {\n vector<long long> freq(1e5 + 1, 0);\n long long sum = 0;\n int max_number = 1;\n for (int &n: nums) {\n freq[n] += 1;\n max_number = max(max_number, n);\n }\n \n vector<long long> freqSum(1e5 + 1, 0);\n for (int i = 1;i <= max_number; i++) \n {\n freqSum[i] = freqSum[i - 1] + freq[i];\n }\n \n \n for (int i = 1;i <= max_number;i = i + 1)\n {\n if (freq[i] == 0)\n continue;\n int j = i;\n for (;j <= max_number;j = j + i) \n {\n long long div = j/i;\n long long total_cases = freqSum[j - 1] - freqSum[j - i];\n long long value = ((freq[i] * total_cases * (div - 1))%mod + (freq[i] * freq[j] * div)%mod)%mod;\n sum = (sum + value)%mod;\n }\n \n if (max_number%i) {\n long long div = max_number/i;\n long long total_cases = freqSum[max_number] - freqSum[j - i];\n sum = (sum + (freq[i] * total_cases * div)%mod)%mod;\n }\n cout << endl;\n }\n \n return sum;\n }\n};\n```\n\nPlease let me know in comments if something is not clear in my code, Happy to share | 0 | 0 | [] | 0 |
sum-of-floored-pairs | A simple, easy to understand solution using prefix sum | a-simple-easy-to-understand-solution-usi-yy2n | \nclass Solution {\npublic:\n int sumOfFlooredPairs(vector<int>& nums) {\n long mod = 1000000007;\n long sum = 0;\n \n int mx = I | harshitgupta526 | NORMAL | 2021-08-26T17:06:13.537926+00:00 | 2021-08-26T17:07:24.589839+00:00 | 304 | false | ```\nclass Solution {\npublic:\n int sumOfFlooredPairs(vector<int>& nums) {\n long mod = 1000000007;\n long sum = 0;\n \n int mx = INT_MIN;\n for(int i=0; i<nums.size(); i++)\n mx = max(mx, nums[i]);\n\n vector<int> freq(mx+1);\n for(int num : nums)\n freq[num]++;\n for(int i=1; i<=mx; i++ )\n freq[i] += freq[i-1];\n \n unordered_set<int> uniqueNumbers;\n for(int num:nums)\n uniqueNumbers.insert(num);\n for(int num : uniqueNumbers)\n {\n int i=2;\n long tempSum = 0;\n while(num*i <=mx)\n {\n int sameFloor = freq[num*i-1]-freq[num*(i-1)-1];\n long sameFloorSum = (sameFloor * (i-1)) % mod;\n tempSum = (tempSum + sameFloorSum) % mod;\n i++;\n }\n int sameFloor = freq[mx]-freq[num*(i-1)-1];\n long sameFloorSum = (sameFloor * (i-1)) % mod;\n tempSum = (tempSum + sameFloorSum) % mod;\n sum = (sum + (tempSum * (freq[num] - freq[num-1]))%mod)%mod;\n }\n return (int)sum;\n\n }\n};\n``` | 0 | 0 | [] | 0 |
sum-of-floored-pairs | beat 100% javascript | beat-100-javascript-by-zsjzsj-rhbd | js\n/**\n * @param {number[]} nums\n * @return {number}\n */\n// [2,5,9]\n// Runtime: 212 ms, faster than 100.00% of JavaScript online submissions for Sum of Fl | zsjzsj | NORMAL | 2021-08-14T11:46:10.675455+00:00 | 2021-08-14T11:46:10.675482+00:00 | 146 | false | ```js\n/**\n * @param {number[]} nums\n * @return {number}\n */\n// [2,5,9]\n// Runtime: 212 ms, faster than 100.00% of JavaScript online submissions for Sum of Floored Pairs.\n// Memory Usage: 51.6 MB, less than 50.00% of JavaScript online submissions for Sum of Floored Pairs.\n// 1 <= nums[i] <= 10^5\nexport default (nums) => {\n const MODULUS = 1000000007;\n // const MAX = 100000;\n let MAX = 0;\n for (let i = 0; i < nums.length; i++) {\n MAX = Math.max(MAX, nums[i]);\n }\n const counts = new Array(MAX + 1).fill(0);\n\n for (let num of nums) {\n // \u8868\u793Acounts[i] \u8868\u793Ai\u6709\u591A\u5C11\u4E2A\u6570\n ++counts[num];\n }\n\n for (let i = 1; i <= MAX; ++i) {\n // \u5347\u7EA7\u6210\u524D\u7F00\u548C\uFF0C\u8868\u793A\u5C0F\u4E8E\u7B49\u4E8Ei\u7684\u6709\u591A\u5C11\u4E2A\u6570\n counts[i] += counts[i - 1];\n }\n\n let total = 0;\n // \u5F53floor(x/y) y\u7B49\u4E8Ei\u7684\u65F6\u5019\uFF0C\u6709\u591A\u5C11\u4E2Ax\n for (let i = 1; i <= MAX; ++i) {\n // \u5728\u8FD9\u4E2A\u8303\u56F4\u5B58\u5728i\n if (counts[i] > counts[i - 1]) {\n let sum = 0;\n // \u5728floor\uFF08x/y\uFF09\u7B49\u4E8Ej\u7684\u65F6\u5019\uFF0C\u6709\u591A\u5C11\u4E2Ax\n for (let j = 1; i * j <= MAX; ++j) {\n // \n const lower = i * j - 1;\n const upper = i * (j + 1) - 1;\n let maxCount = counts[Math.min(upper, MAX)]\n ? counts[Math.min(upper, MAX)]\n : 0;\n // counts[Math.min(upper, MAX)] - counts[lower]\n sum += (maxCount - counts[lower]) * j;\n }\n //\n total = (total + (sum % MODULUS) * (counts[i] - counts[i - 1])) % MODULUS;\n }\n }\n return total;\n};\n\n``` | 0 | 0 | [] | 0 |
sum-of-floored-pairs | Prefix sum of frequency counts | prefix-sum-of-frequency-counts-by-ojha11-sf4j | \n#define ll long long int\nconst int mod=1e9+7;\nclass Solution {\npublic:\n int sumOfFlooredPairs(vector<int>& a) {\n ll i,n=a.size(),j,mx=-1;\n | ojha1111pk | NORMAL | 2021-07-22T15:07:01.690725+00:00 | 2021-07-22T15:07:01.690769+00:00 | 363 | false | ```\n#define ll long long int\nconst int mod=1e9+7;\nclass Solution {\npublic:\n int sumOfFlooredPairs(vector<int>& a) {\n ll i,n=a.size(),j,mx=-1;\n \n for(i=0;i<n;i++)\n if(mx<a[i])\n mx=a[i];\n \n bool vis[mx+10];\n memset(vis,0,sizeof(vis));\n \n ll mxx=mx<<2;\n \n ll f[10+mxx],pf[10+mxx];\n memset(f,0,sizeof(f));\n \n for(i=0;i<n;i++)\n f[a[i]]++;\n \n pf[0]=f[0];\n for(i=1;i<10+mxx;i++)\n pf[i]=pf[i-1]+f[i];\n \n ll ans=0;\n \n for(j=0;j<n;j++){\n i=a[j];\n if(vis[i])\n continue;\n \n vis[i]=1;\n ll left=i-1,right=2*i-1,mf=1;\n ll cntl=pf[left],cntr=pf[right];\n \n while(left<=mx){\n ans=(ans+(mf*(f[i]*(cntr-cntl))%mod)%mod)%mod;\n \n left+=i;\n right+=i;\n \n cntl=pf[left];\n cntr=pf[right];\n \n mf++;\n }\n }\n \n return ans;\n }\n};\n``` | 0 | 3 | ['C', 'Prefix Sum', 'C++'] | 0 |
sum-of-floored-pairs | Python3 Binary Search And Sort | python3-binary-search-and-sort-by-true-d-mvoi | \nclass Solution:\n def sumOfFlooredPairs(self, nums):\n counter = Counter(nums)\n nums.sort()\n res = 0\n for n, c in counter.it | true-detective | NORMAL | 2021-07-13T18:00:57.472165+00:00 | 2021-07-13T18:01:51.652520+00:00 | 231 | false | ```\nclass Solution:\n def sumOfFlooredPairs(self, nums):\n counter = Counter(nums)\n nums.sort()\n res = 0\n for n, c in counter.items():\n multiplier, idx, last_idx = 1, -1, 1\n while idx < len(nums):\n idx = bisect.bisect_left(nums, n*multiplier)\n res += (idx - last_idx) * (multiplier-1) * c\n multiplier += 1\n last_idx = idx\n \n return res % 1_000_000_007\n``` | 0 | 0 | [] | 0 |
sum-of-floored-pairs | Binary search C++ | binary-search-c-by-bombera-dhdb | Not very efficient. But could be accepted.\nUsing binary search.\n\nclass Solution {\npublic:\n int sumOfFlooredPairs(vector<int>& nums) {\n int n = n | bombera | NORMAL | 2021-06-13T01:56:40.287382+00:00 | 2021-06-13T01:57:26.643273+00:00 | 406 | false | Not very efficient. But could be accepted.\nUsing binary search.\n```\nclass Solution {\npublic:\n int sumOfFlooredPairs(vector<int>& nums) {\n int n = nums.size(), mod = 1e9 + 7;\n sort(nums.begin(), nums.end());\n \n long long ret = 0;\n for(int i = 0; i < n;) {\n auto nit = upper_bound(nums.begin(), nums.end(), nums[i]);\n long long cnt = (nit - nums.begin()) - i;\n ret += cnt * (cnt - 1);\n ret %= mod;\n \n int p = nums[i] + nums[i], index = (nit - nums.begin() - 1);\n while(true) {\n auto it = upper_bound(nums.begin(), nums.end(), p - 1);\n if (it == nums.end()) {\n ret += (nums.size() - index) * (p / nums[i] - 1) * cnt;\n ret %= mod;\n break;\n }\n ret += ((it - nums.begin()) - index) * (p / nums[i] - 1) * cnt;\n ret %= mod;\n p += nums[i];\n index = (it - nums.begin());\n }\n i += cnt;\n }\n return ret;\n }\n};\n``` | 0 | 1 | [] | 0 |
sum-of-floored-pairs | Brutal force on binary search to get each range of the multiplication | brutal-force-on-binary-search-to-get-eac-qoqq | scala\n def sumOfFlooredPairs(nums: Array[Int]): Int = {\n val len = nums.length\n if (len == 1) return 1\n import scala.collection.mutable.HashMap\n | qiuqiushasha | NORMAL | 2021-05-31T20:33:20.271835+00:00 | 2021-05-31T20:33:20.271877+00:00 | 169 | false | ```scala\n def sumOfFlooredPairs(nums: Array[Int]): Int = {\n val len = nums.length\n if (len == 1) return 1\n import scala.collection.mutable.HashMap\n val cache = new HashMap[Int, Long]\n nums.sortInPlaceWith(_ <= _)\n val total = nums.reduce(_ + _).toLong\n\n def f(v: Int, k: Int): Int = {\n val target = v * (k + 1) - 1\n var start, mid = 0\n var end = len - 1\n var res = -1\n while (start <= end) {\n mid = (start + end) / 2\n if (nums(mid) <= target) {\n res = Math.max(res, mid)\n start = mid + 1\n } else {\n end = mid - 1\n }\n }\n if (target > nums(len - 1) + v) Integer.MAX_VALUE else res\n }\n\n (nums\n .map(curr => {\n cache.getOrElse(\n curr, {\n var tmp = 0L\n var last = -1\n var k = 0\n var next = f(curr, k)\n while (next != last || next != Integer.MAX_VALUE) {\n if (next != Integer.MAX_VALUE)\n tmp += (next - last) * k\n last = next\n k += 1\n next = f(curr, k)\n }\n cache.put(curr, tmp)\n tmp\n }\n )\n })\n .sum % (Math.pow(10, 9) + 7)).toInt\n\n }\n``` | 0 | 0 | [] | 0 |
sum-of-floored-pairs | Java Binary Search | java-binary-search-by-bigbeautymei-cxxp | \nclass Solution {\n int MOD = 1000000007;\n public int sumOfFlooredPairs(int[] nums) {\n Arrays.sort(nums);\n int n=nums.length,max = nums[ | bigbeautymei | NORMAL | 2021-05-28T22:57:31.302405+00:00 | 2021-05-28T22:57:31.302449+00:00 | 234 | false | ```\nclass Solution {\n int MOD = 1000000007;\n public int sumOfFlooredPairs(int[] nums) {\n Arrays.sort(nums);\n int n=nums.length,max = nums[n-1];\n long res=0;\n \n int count=1;\n for(int i=0;i<n;i++){\n int num = nums[i];\n if(i<n-1&&nums[i+1]==nums[i]){\n count++;\n }else{\n long sum = count;\n int index = i+1;\n for(int k=1;k<=(max/num)+1;k++){\n int newIndex = binarySearch(nums,index,n-1,k*num);\n //System.out.println(k+" "+newIndex+" "+index);\n sum += (newIndex-index)*(k-1);\n index = newIndex;\n }\n res = (res+(sum%MOD)*count)%MOD;\n count=1;\n }\n \n }\n //res+=count*count;\n return (int)res;\n }\n \n // first large or equal than\n public int binarySearch(int[] nums, int left, int right, int target){\n int l = left, r = right;\n while(l<=r){\n int mid = l+(r-l)/2;\n if(nums[mid]>=target){\n r = mid-1;\n }else{\n l = mid+1;\n }\n }\n return l;\n }\n}\n``` | 0 | 0 | [] | 0 |
sum-of-floored-pairs | Prefix sum only , and some minor optimizations to get it in O(nlogn) | prefix-sum-only-and-some-minor-optimizat-23m5 | \nclass Solution {\npublic:\n int maxn=1e5+1;\n int sumOfFlooredPairs(vector<int>& nums) {\n // return 0; \n vector<long long> v(2*maxn+1);\ | rb003 | NORMAL | 2021-05-23T17:14:12.582529+00:00 | 2021-05-23T17:14:12.582576+00:00 | 190 | false | ```\nclass Solution {\npublic:\n int maxn=1e5+1;\n int sumOfFlooredPairs(vector<int>& nums) {\n // return 0; \n vector<long long> v(2*maxn+1);\n long long sum=0, mod=(1e9+7);\n int mxm=0; \n int n=nums.size();\n for(int x: nums) ++v[x], mxm= max(mxm, x);\n for(int i=1;i<=2*maxn; i++) v[i]+=v[i-1];\n set<int> set1(nums.begin(), nums.end());\n for(int x: set1){\n int l=x, r=x*2 -1;\n long long res=1; \n long long sum1=0; \n while( l<=mxm ){\n sum1 = ( sum1 + res*(v[r]- v[l-1]) )% mod;\n l+= x, r+= x; \n res++ ; \n }\n sum1= (sum1 * (v[x]-v[x-1]))%mod;\n sum = (sum + sum1) %mod; \n }\n return sum ; \n }\n};\n```\n | 0 | 0 | [] | 0 |
sum-of-floored-pairs | Python3 - thinking process | python3-thinking-process-by-yunqu-cxup | At the first glance, I would just sort all the elements in order, then iterate for each element nums[i]: increment a factor j from 1, binary search the left bou | yunqu | NORMAL | 2021-05-20T02:01:18.185424+00:00 | 2021-05-20T02:02:54.150761+00:00 | 227 | false | At the first glance, I would just sort all the elements in order, then iterate for each element `nums[i]`: increment a factor `j` from 1, binary search the left boundary of `j * nums[i]`, and the right boundary of `(1 + j) * nums[i] - 1`. This is because all the elements in this range will contribute `j` to the final answer. \nThis approach passed almost all the test cases, but got a TLE for a long repeated test case.\n\n**TLE**\n```python\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n MOD = 10**9 + 7\n nums.sort()\n n = len(nums)\n maxi = max(nums)\n ans = 0\n for i in range(n):\n j = 1\n while j * nums[i] <= maxi:\n left = bisect.bisect_left(nums, j * nums[i])\n right = bisect.bisect_right(nums, (j + 1) * nums[i] - 1)\n ans += j * (right - left)\n j += 1\n return ans % MOD\n```\n\nSo it looks like we should just keep the freqency of the elements, instead of the original nums array. But how do we get how many elements are in the range of `j * nums[i]` to `(1 + j) * nums[i] - 1`? We need some other ways to get all the elements in that range. \n\nAlso, notice that binary search is very time consuming. If we could cache those bounary results, we should not need to do binary searches. We can use prefix array to memorize the number of elements smaller than a particular element. In this way, we can use a simple array access O(1) as opposed to binary search O(log(n)) to quickly figure out\n\n1. how many elements are smaller than `(1 + j) * nums[i] - 1`; and\n2. how many elements smaller than `j * nums[i]` as well). \n\nTake the difference between the above 2 cases, we know how many elements are within that range. \n\nIn the actual implementation, we did it in the reverse way - for each `num` we count how many elements are greater than `j * nums[i]`, since the last group of elements (with the biggest valid `j`) always contribute the most `count[num]` to the answer.\n\n**Final solution**\n```python\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n MOD = 10**9 + 7\n count = Counter(nums)\n n = len(nums)\n maxi = max(nums)\n ans = 0\n \n prefix = [0]\n for i in range(1, maxi + 1):\n prefix += prefix[-1] + count[i],\n\n for num in set(nums):\n for i in range(num, maxi + 1, num):\n ans += count[num] * (prefix[-1] - prefix[i-1])\n return ans % MOD\n``` | 0 | 0 | [] | 0 |
sum-of-floored-pairs | Python Solution | python-solution-by-tarun-mdvu | \nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n maxx, ans=max(nums), 0\n counts=[0]*((maxx*2)+1)\n for i in n | tarun_____ | NORMAL | 2021-05-16T12:40:54.426807+00:00 | 2021-05-16T12:40:54.426850+00:00 | 125 | false | ```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n maxx, ans=max(nums), 0\n counts=[0]*((maxx*2)+1)\n for i in nums: counts[i]+=1\n for i in range(1, len(counts)): counts[i]+=counts[i-1]\n for num in nums:\n l,r,tba=num, (num*2)-1,1\n while l<=maxx:\n ans+=tba*(counts[r]-counts[l-1])\n tba+=1\n l+=num\n r+=num\n return ans%1000000007\n``` | 0 | 0 | [] | 0 |
sum-of-floored-pairs | [C++] | Upper_bound + Basic Maths | c-upper_bound-basic-maths-by-valorant_19-vryo | \nclass Solution {\npublic:\n int mod = 1e9+7;\n int sumOfFlooredPairs(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int res=0;\n | valorant_19 | NORMAL | 2021-05-16T10:21:40.826632+00:00 | 2021-05-17T08:43:34.073884+00:00 | 123 | false | ```\nclass Solution {\npublic:\n int mod = 1e9+7;\n int sumOfFlooredPairs(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int res=0;\n for(int i=0;i<nums.size();i++)\n {\n int prev_index=0,val=-1,cnt=1;\n while(1)\n {\n val++;\n int curr_index = upper_bound(nums.begin()+prev_index,nums.end(),(cnt*nums[i]-1))-nums.begin();\n res = (res % mod + (val * (curr_index - prev_index)) % mod) % mod;\n prev_index = curr_index,cnt++;\n if(curr_index==nums.size())\n break;\n }\n }\n return res;\n }\n};\n``` | 0 | 1 | ['C'] | 0 |
sum-of-floored-pairs | C++ Binary Search + Sieve Approach | c-binary-search-sieve-approach-by-yuvraj-r78n | \n\n\nint sumOfFlooredPairs(vector<int>& nums) {\n long long ans = 0;\n long long mod = 1000000007;\n \n sort(nums.begin(),nums.end( | yuvrajpuyam | NORMAL | 2021-05-15T20:13:47.025286+00:00 | 2021-05-15T20:13:47.025317+00:00 | 124 | false | \n\n```\nint sumOfFlooredPairs(vector<int>& nums) {\n long long ans = 0;\n long long mod = 1000000007;\n \n sort(nums.begin(),nums.end());\n \n int n = nums.size();\n long long curans = 0;\n for(int i = 0 ; i < n; ++i){\n int prev = i;\n int jump = 2;\n if(i > 0 and nums[i] == nums[i-1]) { // If similar value add precomputed value.\n ans += curans;\n continue;\n }\n curans = 0;\n while(true){\n auto cur = lower_bound(nums.begin(),nums.end(),nums[i]*jump) - nums.begin(); \n \n curans =( curans + ((cur-prev)%mod)*((jump-1)%mod))%mod;\n prev = cur;\n jump++;\n if(cur == n) break;\n }\n ans = (ans + curans)%mod;\n }\n return (int) ans;\n }\n``` | 0 | 0 | ['Binary Search'] | 0 |
sum-of-floored-pairs | [Python3] Prefix Sum [O(n log n)] using sets to take care of duplicates | python3-prefix-sum-on-log-n-using-sets-t-nrbi | \nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n \n maximum = 10**5+1\n freq = [0]*(maximum)\n mx = num | rajat499 | NORMAL | 2021-05-15T18:46:01.873412+00:00 | 2021-05-15T18:49:41.944641+00:00 | 82 | false | ```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n \n maximum = 10**5+1\n freq = [0]*(maximum)\n mx = nums[0]\n for n in nums:\n freq[n] += 1\n mx = max(mx, n)\n\n mod = 10**9 + 7\n for i in range(1, maximum):\n freq[i] += freq[i-1]\n\n res = 0\n\n done = set()\n for n in nums:\n if n in done:\n continue\n done.add(n)\n l, r = n, 2*n-1\n i = 1\n sum = 0\n while(l<=mx):\n sum = (sum + i*(freq[min(r, mx)] - freq[l-1]))%mod\n i += 1\n l += n\n r += n\n res = (res + sum*(freq[n]-freq[n-1]))%mod\n return res\n``` | 0 | 0 | [] | 0 |
calculate-digit-sum-of-a-string | ✅✅C++ || Easy Solution || 0ms || Faster | c-easy-solution-0ms-faster-by-himanshu_5-yfkc | \'\'\'\nclass Solution {\npublic:\n\n string digitSum(string s, int k) {\n string ans;\n while(1){\n \n if(s.length()<=k) | himanshu_52 | NORMAL | 2022-04-17T04:06:34.006181+00:00 | 2022-04-17T04:06:34.006211+00:00 | 4,654 | false | \'\'\'\nclass Solution {\npublic:\n\n string digitSum(string s, int k) {\n string ans;\n while(1){\n \n if(s.length()<=k) return s;\n \n int sum=0;\n for(int i=0;i<s.size();i++){\n if(i!=0 and i%k==0){\n ans+=to_string(sum);\n sum=0;\n }\n sum+=(s[i]-\'0\');\n }//end of for\n \n ans+=to_string(sum);\n s=ans;\n ans="";\n \n }//end of while\n }\n};\n\n\'\'\'\n\nPlease Upvote if you like the Solution.\n\uD83D\uDE42 | 47 | 1 | ['String', 'C'] | 6 |
calculate-digit-sum-of-a-string | Recursive Java Solution, 11 lines | recursive-java-solution-11-lines-by-clim-i23c | ```java\n public String digitSum(String s, int k){\n if(s.length() <= k)\n return s;\n StringBuilder r = new StringBuilder();\n | climberig | NORMAL | 2022-04-17T04:45:57.159823+00:00 | 2022-04-17T04:47:46.383254+00:00 | 1,776 | false | ```java\n public String digitSum(String s, int k){\n if(s.length() <= k)\n return s;\n StringBuilder r = new StringBuilder();\n for(int i = 1, sum = 0; i <= s.length(); i++){\n sum += s.charAt(i - 1) - \'0\';\n if(i % k == 0 || i == s.length()){\n r.append(sum);\n sum = 0;\n }\n }\n return digitSum(r.toString(), k);\n } | 28 | 1 | ['Java'] | 2 |
calculate-digit-sum-of-a-string | Simple Java Solution with comments for understanding | simple-java-solution-with-comments-for-u-s4p4 | \nclass Solution {\n public String digitSum(String s, int k) {\n while(s.length()>k){\n String ns=""; // replace the old string with update | m0rnings8ar | NORMAL | 2022-04-17T04:01:12.375485+00:00 | 2022-04-17T04:01:12.375530+00:00 | 3,576 | false | ```\nclass Solution {\n public String digitSum(String s, int k) {\n while(s.length()>k){\n String ns=""; // replace the old string with updated one\n for(int i=0;i<s.length();i+=k){\n String t=s.substring(i,Math.min(i+k,s.length())); // form the string of k size\n int sum=0;\n for(int l=0;l<t.length();l++){ // to find the character sum of string t\n sum+=t.charAt(l)-\'0\';\n }\n ns+="" + sum; //update the string with sum of k size string character \n }\n s=ns; //update the old string with updated one\n }\n return s;\n }\n}\n```\nUpvote if it\'s helpful | 28 | 0 | ['Array', 'String', 'Java'] | 5 |
calculate-digit-sum-of-a-string | Python3 elegant pythonic clean and easy to understand | python3-elegant-pythonic-clean-and-easy-10z68 | Simple while loop and slicing to repeat 3 set process and aggregation\n\n\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s | tallicia | NORMAL | 2022-04-17T04:08:29.165074+00:00 | 2022-04-17T04:24:37.637935+00:00 | 2,666 | false | Simple while loop and slicing to repeat 3 set process and aggregation\n\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n set_3 = [s[i:i+k] for i in range(0, len(s), k)]\n s = \'\'\n for e in set_3:\n val = 0\n for n in e:\n val += int(n)\n s += str(val)\n return s\n```\n\ncan be condensed and more pythonic:\n\n```\n while len(s) > k:\n set_3 = [s[i:i+k] for i in range(0, len(s), k)]\n s = \'\'\n for e in set_3:\n s += str(sum([int(n) for n in e]))\n return s\n``` | 19 | 0 | ['Python', 'Python3'] | 4 |
calculate-digit-sum-of-a-string | Accumulate | accumulate-by-votrubac-pokz | C++\ncpp\nstring digitSum(string s, int k) {\n while(s.size() > k) {\n string s1;\n for (int i = 0; i < s.size(); i += k)\n s1 += to | votrubac | NORMAL | 2022-04-17T04:28:19.407169+00:00 | 2022-04-17T04:28:19.407195+00:00 | 2,314 | false | **C++**\n```cpp\nstring digitSum(string s, int k) {\n while(s.size() > k) {\n string s1;\n for (int i = 0; i < s.size(); i += k)\n s1 += to_string(accumulate(begin(s) + i, begin(s) + min((int)s.size(), i + k), 0, \n [](int n, char ch){ return n + ch - \'0\'; }));\n swap(s1, s);\n }\n return s;\n}\n``` | 18 | 0 | ['C'] | 5 |
calculate-digit-sum-of-a-string | C++ Easy to understand (Single loop and recursive) | c-easy-to-understand-single-loop-and-rec-tw9e | \nclass Solution {\npublic:\n string digitSum(string s, int k) {\n \n if(s.length()<=k)\n return s;\n \n string ans="" | NeerajSati | NORMAL | 2022-04-17T04:04:37.988280+00:00 | 2022-04-17T04:17:57.159056+00:00 | 1,905 | false | ```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n \n if(s.length()<=k)\n return s;\n \n string ans="";\n int sum=0,temp=k;\n int len = s.length();\n for(int i=0;i<len;i++){\n sum += (s[i] -\'0\');\n temp--;\n if(temp==0){\n ans+= to_string(sum);\n temp=k;\n sum=0;\n }\n }\n if(temp!=k){\n ans+= to_string(sum);\n }\n if(ans.length()>k)\n ans = digitSum(ans,k);\n return ans;\n }\n};\n``` | 17 | 0 | ['String', 'C'] | 4 |
calculate-digit-sum-of-a-string | A Concise JavaScript Solution | a-concise-javascript-solution-by-curfeu-7m8z | \nvar digitSum = function(s, k) {\n while (s.length > k) {\n let newString = "";\n for (let i = 0; i < s.length; i += k)\n newString | curfeu | NORMAL | 2022-04-17T17:28:20.672024+00:00 | 2022-04-17T17:44:12.237340+00:00 | 729 | false | ```\nvar digitSum = function(s, k) {\n while (s.length > k) {\n let newString = "";\n for (let i = 0; i < s.length; i += k)\n newString += s.substring(i, i + k).split("").reduce((acc, val) => acc + (+val), 0);\n \n s = newString;\n }\n \n return s;\n};\n``` | 14 | 0 | ['JavaScript'] | 2 |
calculate-digit-sum-of-a-string | 2243. Calculate Digit Sum of a String, Time complexity: O(N^2), Space complexity: O(N) | 2243-calculate-digit-sum-of-a-string-tim-ofp5 | IntuitionApproachComplexity
Time complexity: O(N^2)
Space complexity: O(N)
Code | richardmantikwang | NORMAL | 2024-12-21T02:31:05.461035+00:00 | 2024-12-21T02:31:05.461035+00:00 | 250 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(N^2)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def digitSum(self, s, k):
len_s = len(s)
while (len_s > k):
new_s = ''
start_index = 0
end_pos = start_index + k
while (start_index < len_s):
substr = s[start_index:end_pos]
sum_digits = sum([int(d) for d in list(substr)])
new_s += str(sum_digits)
start_index += k
end_pos += k
s = new_s
len_s = len(s)
return s
``` | 11 | 0 | ['Python3'] | 0 |
calculate-digit-sum-of-a-string | Python 6line code || 98.60 %Beats || Simple Code | python-6line-code-9860-beats-simple-code-7fed | If you got help from this,... Plz Upvote .. it encourage me\n# Code\nShort Way:\n\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n whil | vvivekyadav | NORMAL | 2023-09-27T13:38:00.018577+00:00 | 2023-09-27T13:38:00.018600+00:00 | 506 | false | **If you got help from this,... Plz Upvote .. it encourage me**\n# Code\nShort Way:\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n new_s = \'\'\n for i in range(0,len(s), k):\n new_s += str(sum(int(d) for d in s[i:i+k]))\n s = new_s \n return s\n\n \n```\n.\nSame Approach but long way to understand.\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n new_s = \'\'\n for i in range(0,len(s), k):\n temp = 0\n for d in s[i:i+k]:\n temp += int(d)\n \n new_s += str(temp)\n\n s = new_s\n \n return s\n``` | 7 | 0 | ['String', 'Python', 'Python3'] | 1 |
calculate-digit-sum-of-a-string | C++ solution | c-solution-by-navneetkchy-povx | \nclass Solution {\npublic:\n string digitSum(string s, int k) {\n while ((int) s.size() > k) {\n int sum = 0;\n string t = "";\ | navneetkchy | NORMAL | 2022-04-17T04:05:13.458210+00:00 | 2022-04-17T04:05:13.458247+00:00 | 998 | false | ```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n while ((int) s.size() > k) {\n int sum = 0;\n string t = "";\n int count = 0;\n for (int i = 0; i < (int) s.size(); i++) {\n sum += (s[i] - \'0\');\n ++count;\n if (count == k) {\n t += to_string(sum);\n sum = 0;\n count = 0;\n }\n }\n if (count > 0) {\n t += to_string(sum);\n }\n s = t;\n }\n return s;\n }\n};\n``` | 7 | 0 | [] | 2 |
calculate-digit-sum-of-a-string | ✅ [C] || 100% Fast Solution || Beginner-Friendly | c-100-fast-solution-beginner-friendly-by-qws5 | \nchar * digitSum(char * s, int k) {\n int cur = 0;\n int sum = 0;\n for (int i = 0; strlen(s) > k; i++) {\n if (i != 0 && i % k == 0 || i == st | bezlant | NORMAL | 2022-04-17T04:03:04.730845+00:00 | 2022-04-17T04:07:45.261889+00:00 | 516 | false | ```\nchar * digitSum(char * s, int k) {\n int cur = 0;\n int sum = 0;\n for (int i = 0; strlen(s) > k; i++) {\n if (i != 0 && i % k == 0 || i == strlen(s)) {\n char buff[16];\n sprintf(buff, "%d", sum);\n for (int i = 0; buff[i]; i++, cur++)\n s[cur] = buff[i];\n sum = 0;\n }\n if (i == strlen(s)) { \n s[cur] = \'\\0\';\n cur = 0;\n i = 0;\n }\n sum += s[i] - \'0\';\n }\n \n return s;\n}\n```\n\n**If this was helpful, don\'t hesitate to upvote! :)**\nHave a nice day! | 6 | 1 | ['C'] | 3 |
calculate-digit-sum-of-a-string | Simple Python Solution | simple-python-solution-by-ancoderr-m0nx | \nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n def divideString(s: str, k: int) -> List[str]: # Utility function to return list of d | ancoderr | NORMAL | 2022-04-17T04:02:57.382849+00:00 | 2022-04-17T04:19:31.060920+00:00 | 1,389 | false | ```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n def divideString(s: str, k: int) -> List[str]: # Utility function to return list of divided groups.\n l, n = [], len(s)\n for i in range(0, n, k):\n l.append(s[i:min(i + k, n)])\n return l\n while len(s)>k: # Till size of s is greater than k\n arr, temp = divideString(s, k), [] # arr is the list of divided groups, temp will be the list of group sums\n for group in arr: # Traverse the group and add its digits\n group_sum = 0\n for digit in group:\n group_sum += int(digit)\n temp.append(str(group_sum)) # Sum of digits of current group\n s = \'\'.join(temp) # s is replaced by the group digit sum for each group.\n return s\n``` | 6 | 0 | ['Python', 'Python3'] | 1 |
calculate-digit-sum-of-a-string | [Python 3] Convert string to list and use brute-force | python-3-convert-string-to-list-and-use-ln7tv | python3 []\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n s = list(map(int, s))\n while len(s) > k:\n tmp = []\n | yourick | NORMAL | 2023-07-25T22:12:26.906410+00:00 | 2023-08-14T14:14:17.094272+00:00 | 393 | false | ```python3 []\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n s = list(map(int, s))\n while len(s) > k:\n tmp = []\n for i in range(0, len(s), k):\n S = sum(s[i:i+k])\n for d in (str(S)):\n tmp.append(int(d))\n s = tmp\n\n return \'\'.join(map(str, s))\n``` | 5 | 0 | ['Python', 'Python3'] | 0 |
calculate-digit-sum-of-a-string | Java Easy Consise | java-easy-consise-by-bharat194-cb83 | \nclass Solution {\n public String digitSum(String s, int k) {\n while(s.length() > k) s = gen(s,k);\n return s;\n }\n public String gen( | bharat194 | NORMAL | 2022-04-17T18:37:45.871779+00:00 | 2022-04-17T18:37:45.871819+00:00 | 638 | false | ```\nclass Solution {\n public String digitSum(String s, int k) {\n while(s.length() > k) s = gen(s,k);\n return s;\n }\n public String gen(String s,int k){\n String res = "";\n for(int i=0;i < s.length();){\n int count = 0,num=0;\n while(i < s.length() && count++ < k) num += Character.getNumericValue(s.charAt(i++));\n res+=num;\n }\n return res;\n }\n}\n``` | 5 | 0 | ['Java'] | 1 |
calculate-digit-sum-of-a-string | JAVA SOLUTION RECURSION 🦘 | java-solution-recursion-by-sulaymon-dev2-g0ri | \nclass Solution {\n public String digitSum(String s, int k) {\n return s.length() > k ? digitSum(new StringBuilder(s), k) : s;\n }\n\n public S | Sulaymon-Dev20 | NORMAL | 2022-09-01T10:42:33.721350+00:00 | 2022-09-01T10:42:33.721397+00:00 | 598 | false | ```\nclass Solution {\n public String digitSum(String s, int k) {\n return s.length() > k ? digitSum(new StringBuilder(s), k) : s;\n }\n\n public String digitSum(StringBuilder numbers, int k) {\n StringBuilder res = new StringBuilder(numbers.length() / k + 1);\n for (int i = 0, loop = 0, sum = 0; i < numbers.length(); i++) {\n sum += numbers.charAt(i) - \'0\';\n if (++loop == k || numbers.length() - 1 == i) {\n res.append(sum);\n sum = 0;\n loop = 0;\n }\n }\n return res.length() > k ? digitSum(res, k) : res.toString();\n }\n}\n``` | 4 | 0 | ['String', 'Recursion', 'Java'] | 0 |
calculate-digit-sum-of-a-string | easy | easy-by-qwerysingr-3027 | \nclass Solution {\npublic:\n string digitSum(string s, int k) {\n \n while (true) {\n int n(size(s));\n int cnt(0), curr | qwerysingr | NORMAL | 2022-05-08T05:54:15.063495+00:00 | 2022-05-08T05:54:15.063527+00:00 | 154 | false | ```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n \n while (true) {\n int n(size(s));\n int cnt(0), curr(0), i(0);\n string nn;\n if (size(s) <= k) break;\n while (i < n) {\n curr += s[i++]-\'0\';\n if (++cnt == k or i == n) {\n cout << curr << "\\n";\n nn += to_string(curr);\n curr = 0;\n cnt = 0;\n }\n }\n s = nn;\n }\n return s;\n }\n};\n``` | 4 | 0 | [] | 0 |
calculate-digit-sum-of-a-string | [Java] 0ms + EASY explanations | java-0ms-easy-explanations-by-stefanelst-cf06 | \nclass Solution {\n /** Algorithm\n 1. While s is longer than k, try to add its digits into a string builder stb\n 2. Loop in windows of k s | StefanelStan | NORMAL | 2022-04-22T21:29:52.038952+00:00 | 2022-04-22T22:02:32.597988+00:00 | 411 | false | ```\nclass Solution {\n /** Algorithm\n 1. While s is longer than k, try to add its digits into a string builder stb\n 2. Loop in windows of k size and continue ONLY if current index < s.length().\n (meaning current expanding window is still shorter than s.length())\n EG: "123456789", k = 4. window1 : "1,2,3,4", window2 = "5,6,7,8"\n 3. In an inner loop, loop with j from i to i+ k; stopping at i + k OR when j reaches s.length() -1 \n Add digits to a temp int and add it to string builder \n 4. Make s point to the string value of the string builder.\n 5. Return s.\n */\n public String digitSum(String s, int k) {\n StringBuilder stb = new StringBuilder();\n int temp = 0;\n while(s.length() > k) {\n stb.setLength(0);\n for(int i = 0; i < s.length(); i += k) {\n temp = 0;\n for(int j = i; j < i + k && j < s.length(); j++) {\n temp += s.charAt(j) - \'0\';\n }\n stb.append(temp);\n }\n s = stb.toString();\n }\n return s;\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
calculate-digit-sum-of-a-string | JavaScript | javascript-by-netant007-82fs | \nwhile(s.length>k){\n\tlet temp=\'\'\n\tfor(let q=0;q<s.length;q+=k){\n\t\ttemp+=eval(s.substring(q,q+k).split(\'\').join(\'+\'))\n\t}\n\ts=temp\n}\nreturn s\n | netant007 | NORMAL | 2022-04-17T05:08:32.250464+00:00 | 2022-04-17T05:08:32.250511+00:00 | 296 | false | ```\nwhile(s.length>k){\n\tlet temp=\'\'\n\tfor(let q=0;q<s.length;q+=k){\n\t\ttemp+=eval(s.substring(q,q+k).split(\'\').join(\'+\'))\n\t}\n\ts=temp\n}\nreturn s\n``` | 4 | 0 | ['JavaScript'] | 1 |
calculate-digit-sum-of-a-string | Simple while loop | simple-while-loop-by-theabbie-lbsu | \nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n nexts = ""\n for i in range(0, len(s), k):\ | theabbie | NORMAL | 2022-04-17T04:03:00.242420+00:00 | 2022-04-17T04:03:00.242448+00:00 | 348 | false | ```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n nexts = ""\n for i in range(0, len(s), k):\n nexts += str(sum(int(d) for d in s[i:i+k]))\n s = nexts\n return s\n``` | 4 | 0 | ['Python'] | 1 |
calculate-digit-sum-of-a-string | here is my solution->>:) | here-is-my-solution-by-re__fresh-gsdi | *plz upvote if you find my solution helpful***\n\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n l=len(s)\n \n while(l>k):\n | re__fresh | NORMAL | 2022-09-07T17:52:39.864446+00:00 | 2022-09-07T17:52:39.864486+00:00 | 382 | false | *****plz upvote if you find my solution helpful*****\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n l=len(s)\n \n while(l>k):\n s1=""\n for i in range(0,len(s),k):#0 -10\n \n sm=0\n for j in range(i,i+k):\n if(j<len(s)):\n sm+=int(s[j])\n s1=s1+str(sm)\n \n s=s1\n l=len(s)\n return s\n``` | 3 | 0 | ['Python'] | 0 |
calculate-digit-sum-of-a-string | Calculate Digit Sum of a String Solution Java | calculate-digit-sum-of-a-string-solution-d300 | class Solution {\n public String digitSum(String s, int k) {\n while (s.length() > k) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0 | bhupendra786 | NORMAL | 2022-08-16T08:32:48.290201+00:00 | 2022-08-16T08:32:48.290248+00:00 | 140 | false | class Solution {\n public String digitSum(String s, int k) {\n while (s.length() > k) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < s.length(); i += k) {\n int sum = 0;\n for (int j = i; j < Math.min(s.length(), i + k); ++j)\n sum += s.charAt(j) - \'0\';\n sb.append(sum);\n }\n s = sb.toString();\n }\n return s;\n }\n}\n | 3 | 0 | ['String', 'Simulation'] | 0 |
calculate-digit-sum-of-a-string | C# One-Liner, Recursion, LINQ | c-one-liner-recursion-linq-by-rad0mir-m0ni | \npublic class Solution \n{\n public string DigitSum(string s, int k) \n => s.Length <= k ? s : DigitSum(String.Concat(s.Chunk(k).Select(g => g.Sum(c | Rad0miR | NORMAL | 2022-04-17T18:33:29.474947+00:00 | 2022-04-17T18:33:29.474987+00:00 | 147 | false | ```\npublic class Solution \n{\n public string DigitSum(string s, int k) \n => s.Length <= k ? s : DigitSum(String.Concat(s.Chunk(k).Select(g => g.Sum(c => c - \'0\'))), k);\n}\n``` | 3 | 0 | ['Recursion'] | 1 |
calculate-digit-sum-of-a-string | Rust solution | rust-solution-by-bigmih-97z0 | \nimpl Solution {\n pub fn digit_sum(s: String, k: i32) -> String {\n let mut s = s;\n while s.len() > k as usize {\n s = s\n | BigMih | NORMAL | 2022-04-17T14:00:54.393603+00:00 | 2022-04-17T14:00:54.393637+00:00 | 129 | false | ```\nimpl Solution {\n pub fn digit_sum(s: String, k: i32) -> String {\n let mut s = s;\n while s.len() > k as usize {\n s = s\n .chars()\n .collect::<Vec<_>>()\n .chunks(k as usize)\n .map(|chunk| {\n chunk\n .iter()\n .map(|c| c.to_digit(10).unwrap())\n .sum::<u32>()\n .to_string()\n })\n .collect::<Vec<_>>()\n .join("");\n }\n s\n }\n}\n``` | 3 | 0 | ['Rust'] | 1 |
calculate-digit-sum-of-a-string | Java | Simple | java-simple-by-shubham203-xtdx | ```\npublic String digitSum(String s, int k) {\n StringBuilder sb = new StringBuilder(s);\n while (sb.length()>k) {\n int idx = 0;\n | shubham203 | NORMAL | 2022-04-17T04:04:31.952360+00:00 | 2022-04-17T04:04:31.952388+00:00 | 307 | false | ```\npublic String digitSum(String s, int k) {\n StringBuilder sb = new StringBuilder(s);\n while (sb.length()>k) {\n int idx = 0;\n StringBuilder curr = new StringBuilder();\n while (idx<sb.length()) {\n String ss = sb.toString().substring(idx, Math.min(idx+k,sb.length()));\n idx+=k;\n int value = 0;\n for (char c: ss.toCharArray()) {\n value = value + (c-\'0\');\n }\n curr.append(value);\n }\n sb = new StringBuilder(curr);\n }\n \n return sb.toString();\n } | 3 | 0 | [] | 1 |
calculate-digit-sum-of-a-string | C++ || Easy To Understand || Simple Brute Force Approach | c-easy-to-understand-simple-brute-force-3v9va | \nclass Solution {\npublic:\n int help(string &s)\n {\n int d=0;\n for(int i=0;i<s.length();i++)\n {\n d+=(s[i]-\'0\');\n | aarindey | NORMAL | 2022-04-17T04:04:25.565747+00:00 | 2022-04-17T04:04:25.565780+00:00 | 301 | false | ```\nclass Solution {\npublic:\n int help(string &s)\n {\n int d=0;\n for(int i=0;i<s.length();i++)\n {\n d+=(s[i]-\'0\');\n }\n return d;\n }\n string digitSum(string s, int k) {\n int n=s.length();\n string temp=s,neww;\n if(k>=n)\n return s;\n while(temp.size()>k)\n {\n neww="";\n for(int i=0;i<temp.size();i+=k)\n {\n string str=temp.substr(i,min((int)k,(int)(temp.size()-i)));\n string sum=to_string(help(str));\n neww+=sum;\n }\n temp=neww;\n }\n return neww;\n }\n};\n```\n**Please upvote to motivate me in my quest of documenting all leetcode solutions(to help the community). HAPPY CODING:)\nAny suggestions and improvements are always welcome** | 3 | 0 | [] | 2 |
calculate-digit-sum-of-a-string | Iterative Digit Summation and Reduction Beats 100% Of the Submissions | iterative-digit-summation-and-reduction-5jm6t | IntuitionThe problem requires repeatedly dividing the string into groups of size k , summing the digits in each group, and forming a new string until the lengt | x7Fg9_K2pLm4nQwR8sT3vYz5bDcE6h | NORMAL | 2025-02-24T13:13:41.922949+00:00 | 2025-02-24T13:13:41.922949+00:00 | 65 | false | # Intuition
The problem requires repeatedly dividing the string into groups of size k , summing the digits in each group, and forming a new string until the length of the string is at most k . This suggests an iterative approach where we repeatedly process the string, reducing its length each time.
# Approach
1. Iterate While Length is Greater than k :
- Continue processing the string until its length becomes less than equal to k.
2. Grouping and Summation:
- Traverse the string and sum up digits in groups of size k .
- If the last group is smaller than k , process it separately.
3. Forming the New String:
- Convert the sum of each group into a string and concatenate to form the new string.
- Repeat the process until the length constraint is met.
The approach ensures that the string is reduced efficiently in each round until it satisfies the problem condition.
# Complexity
- Time complexity: $$O(n)$$ per iteration, where n is the length of the string. Since the string shrinks after every iteration, the number of iterations is logarithmic in n . The worst-case complexity is approximately $$O(nlogn)$$.
- Space complexity: $$O(n)$$ for storing the intermediate strings.
# Code
```cpp []
class Solution {
public:
string digitSum(string s, int k) {
while (s.size()>k){
string b="";
for (int i=0,l=0;i<s.size();i++){
l+=s[i]-'0';
if (((i+1)%k==0)||(i==s.size()-1)){b+=to_string(l);l=0;}
}
s=b;
}
return s;
}
};
``` | 2 | 0 | ['C++'] | 0 |
calculate-digit-sum-of-a-string | Python || Easy Solution | python-easy-solution-by-kumarcharukesh-62a1 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | kumarcharukesh | NORMAL | 2024-07-30T10:49:32.228565+00:00 | 2024-07-30T10:49:32.228599+00:00 | 85 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def digitSum(self,s,k):\n n=len(s)\n while n>k:\n s2=""\n k1=k\n for i in range(0,n,k):\n s1=s[i:k1]\n k1=k1+k\n sum1=0\n for j in s1:\n sum1=sum1+int(j)\n s2=s2+str(sum1)\n s=s2\n n=len(s)\n return s\n``` | 2 | 0 | ['Python'] | 0 |
calculate-digit-sum-of-a-string | Easy Understandable Soln | JAVA🔥 | easy-understandable-soln-java-by-sumo25-rti0 | \n\n# Code\n\nclass Solution {\n public String digitSum(String s, int k) {\n int i=0;\n while(s.length()>k){\n i=0;\n Str | sumo25 | NORMAL | 2024-02-18T18:37:04.187119+00:00 | 2024-02-18T18:37:04.187142+00:00 | 423 | false | \n\n# Code\n```\nclass Solution {\n public String digitSum(String s, int k) {\n int i=0;\n while(s.length()>k){\n i=0;\n String ans="";\n while(i<s.length()){\n if(i+k>s.length()){\n ans+=find(s.substring(i,s.length()));\n }\n else{\n ans+=find(s.substring(i,i+k));\n } \n i+=k;\n }\n s=ans;\n }\n return s;\n }\n public String find(String s){\n int i=0;\n int sum=0;\n while(i<s.length()){\n sum+=s.charAt(i)-\'0\';\n i++;\n }\n return String.valueOf(sum);\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
calculate-digit-sum-of-a-string | Calculate Digit Sum of a String Solution in C++ | calculate-digit-sum-of-a-string-solution-fy1f | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | The_Kunal_Singh | NORMAL | 2023-06-01T03:51:42.861800+00:00 | 2023-06-01T03:51:42.861832+00:00 | 109 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n*m)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n int i, j=0, l, n;\n string temp="";\n while(s.length()>k)\n {\n j=0;\n l = s.length()/k;\n while(l--)\n {\n for(i=j ; i<j+k ; i++)\n {\n n += s[i]-48;\n }\n j = j+k;\n temp += to_string(n);\n n=0;\n }\n if(s.length()%k!=0)\n {\n for(i=j ; i<s.length() ; i++)\n {\n n += s[i]-48;\n }\n temp += to_string(n);\n n=0;\n }\n s.clear();\n s = temp;\n temp.clear();\n }\n return s;\n }\n};\n```\n\n | 2 | 0 | ['C++'] | 0 |
calculate-digit-sum-of-a-string | Java Easy Solution || Beginner Friendly | java-easy-solution-beginner-friendly-by-vm1vj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | raunakbhanarkar7 | NORMAL | 2023-05-24T01:09:49.428909+00:00 | 2023-05-24T01:09:49.428939+00:00 | 508 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String digitSum(String s, int k) {\n StringBuilder sb = new StringBuilder(s);\n\n // Continue until length of sb is less than or equal to k\n while (sb.length() > k) {\n StringBuilder newString = new StringBuilder();\n int i = 0;\n\n // Iterate over characters of sb\n while (i < sb.length()) {\n int sum = 0;\n int count = 0;\n\n // Calculate sum of digits for each group\n while (i < sb.length() && count < k) {\n sum += sb.charAt(i) - \'0\';\n i++;\n count++;\n }\n\n newString.append(sum);\n }\n\n sb = newString; // Update sb with newString\n }\n\n return sb.toString();\n }\n}\n\n``` | 2 | 0 | ['Java'] | 1 |
calculate-digit-sum-of-a-string | JAVA | calculate-digit-sum-of-a-string | java-calculate-digit-sum-of-a-string-by-facbl | \nclass Solution {\n public String digitSum(String s, int k) {\n if(s.length()<=k)return s;\n while(s.length()>k)\n {\n Strin | Venkat089 | NORMAL | 2022-11-21T12:15:37.012970+00:00 | 2022-11-21T12:15:37.013015+00:00 | 646 | false | ```\nclass Solution {\n public String digitSum(String s, int k) {\n if(s.length()<=k)return s;\n while(s.length()>k)\n {\n String str="";\n int left=s.length()%k;\n for(int i=0;i<s.length()-left;i+=k)\n {\n str+=(sumstring(s.substring(i,i+k)));\n }\n if(s.length()%k!=0)str+=(sumstring(s.substring(s.length()-left,s.length())));\n s=str;\n System.out.println(s);\n }\n return s;\n \n }\n \n public String sumstring(String str){\n int sum=0;\n for(char i:str.toCharArray())\n {\n sum+=(i-\'0\');\n }\n return String.valueOf(sum);\n }\n}\n``` | 2 | 0 | ['String', 'Java'] | 0 |
calculate-digit-sum-of-a-string | the fastest solution run time 97% memory 90% | the-fastest-solution-run-time-97-memory-fg4w7 | \n\n\nclass Solution {\n public static String digitSum(String s, int k) {\n\n StringBuilder stringBuilder = new StringBuilder();\n\n while (s.le | Qurbonali | NORMAL | 2022-11-12T05:18:38.161968+00:00 | 2022-11-12T05:18:38.162006+00:00 | 727 | false | \n\n```\nclass Solution {\n public static String digitSum(String s, int k) {\n\n StringBuilder stringBuilder = new StringBuilder();\n\n while (s.length() > k) {\n\n for (int i = 0; i < s.length(); i+=k) {\n\n if (i+k<=s.length()) stringBuilder.append(sum(s.substring(i, i + k)));\n else stringBuilder.append(sum(s.substring(i)));\n }\n\n s = stringBuilder.toString();\n stringBuilder = new StringBuilder();\n\n }\n\n return s;\n }\n\n public static Integer sum(String number){\n\n int n = 0;\n\n for (int i = 0; i < number.length(); i++) {\n n += Integer.parseInt(number.substring(i,i+1));\n }\n\n return n;\n }\n}\n``` | 2 | 1 | ['Java'] | 0 |
calculate-digit-sum-of-a-string | Java 100% faster | 96% memory solution | java-100-faster-96-memory-solution-by-tb-2rpf | Code\n\nclass Solution {\n public String digitSum(String s, int k) {\n StringBuilder sb = new StringBuilder();\n String intermediate = s;\n | tbekpro | NORMAL | 2022-11-03T04:36:28.255686+00:00 | 2022-11-03T04:36:28.255733+00:00 | 438 | false | # Code\n```\nclass Solution {\n public String digitSum(String s, int k) {\n StringBuilder sb = new StringBuilder();\n String intermediate = s;\n int interInt = 0;\n while (intermediate.length() > k) {\n for (int i = 0; i < intermediate.length(); i += k) {\n for (int j = i; j < i + k && j < intermediate.length(); j++) {\n interInt += intermediate.charAt(j) - \'0\';\n }\n sb.append(interInt);\n interInt = 0;\n }\n intermediate = sb.toString();\n sb.setLength(0);\n }\n return intermediate;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
calculate-digit-sum-of-a-string | ✅✅C++ || Easy Solution || 0ms || Faster | c-easy-solution-0ms-faster-by-akshat0610-e8pi | \nclass Solution {\npublic:\n string digitSum(string s, int k) \n {\n return fun(s,k); \n }\n string fun(string s,int &k)\n {\n \tif(s.leng | akshat0610 | NORMAL | 2022-10-09T17:22:43.114836+00:00 | 2022-10-09T17:22:43.114879+00:00 | 869 | false | ```\nclass Solution {\npublic:\n string digitSum(string s, int k) \n {\n return fun(s,k); \n }\n string fun(string s,int &k)\n {\n \tif(s.length()<=k)\n \t{\n \t\treturn s;\n }\n int idx=0;\n string str="";\n while(idx<s.length())\n {\n \tint sum=0;\n \tint counter=0;\n \twhile(idx<s.length() and counter<k)\n \t{\n \t\tsum=sum+(s[idx]-\'0\');\n \t\tcounter++;\n \t\tidx++;\n\t\t}\n\t\tstr=str+to_string(sum);\n\t}\n\treturn fun(str,k);\n }\n};\n``` | 2 | 0 | ['Recursion', 'C', 'C++'] | 0 |
calculate-digit-sum-of-a-string | EASY TO UNDERSTAND || SIMPLE JAVA CODE | easy-to-understand-simple-java-code-by-p-6unm | \nclass Solution {\n public String digitSum(String s, int k) {\n \n \n while(s.length()>k){\n String temp="",sub;\n | priyankan_23 | NORMAL | 2022-08-29T19:51:52.955990+00:00 | 2022-08-29T19:51:52.956030+00:00 | 231 | false | ```\nclass Solution {\n public String digitSum(String s, int k) {\n \n \n while(s.length()>k){\n String temp="",sub;\n \n for(int i=0;i<s.length();){\n if(i<s.length()+1 && i+k>=s.length()){\n sub=s.substring(i);\n i+=sub.length();\n }else{\n sub=s.substring(i,i+k);\n i+=k;\n }\n int count=0;\n for(char c:sub.toCharArray())count+=c-\'0\';\n temp+=count+"";\n }\n \n s=temp;\n \n \n \n }\n return s;\n \n \n }\n}\n``` | 2 | 0 | [] | 0 |
calculate-digit-sum-of-a-string | Python Elegant & Short | Pythonic | Iterative + Recursive | python-elegant-short-pythonic-iterative-aqny6 | \tclass Solution:\n\t\tdef digitSum(self, s: str, k: int) -> str:\n\t\t\t"""Iterative version"""\n\t\t\twhile len(s) > k:\n\t\t\t\ts = self.round(s, k)\n\t\t\tr | Kyrylo-Ktl | NORMAL | 2022-08-14T19:22:31.717012+00:00 | 2022-08-14T19:25:20.322001+00:00 | 766 | false | \tclass Solution:\n\t\tdef digitSum(self, s: str, k: int) -> str:\n\t\t\t"""Iterative version"""\n\t\t\twhile len(s) > k:\n\t\t\t\ts = self.round(s, k)\n\t\t\treturn s\n\t\n\t\tdef digitSum(self, s: str, k: int) -> str:\n\t\t\t"""Recursive version"""\n\t\t\tif len(s) <= k:\n\t\t\t\treturn s\n\t\t\treturn self.digitSum(self.round(s, k), k)\n\n\t\t@classmethod\n\t\tdef round(cls, s: str, k: int) -> str:\n\t\t\treturn \'\'.join(map(cls.add_digits, cls.slice(s, k)))\n\n\t\t@staticmethod\n\t\tdef add_digits(s: str) -> str:\n\t\t\treturn str(sum(int(d) for d in s))\n\n\t\t@staticmethod\n\t\tdef slice(s: str, k: int):\n\t\t\tfor i in range(0, len(s), k):\n\t\t\t\tyield s[i:i + k]\n | 2 | 0 | ['Python', 'Python3'] | 0 |
calculate-digit-sum-of-a-string | Python Recursive Approach | python-recursive-approach-by-rnyati2000-jnj5 | \nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \n def func(s,k):\n if len(s)<=k:\n return s\n | rnyati2000 | NORMAL | 2022-06-08T14:34:25.520459+00:00 | 2022-06-08T14:34:25.520508+00:00 | 222 | false | ```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \n def func(s,k):\n if len(s)<=k:\n return s\n \n x=""\n a=k\n for i in range(0,len(s),++k):\n y=s[i:i+k]\n z=0\n for j in y:\n z+=int(j)\n x+=str(z) \n return func(x,k)\n \n return func(s,k)\n```\nIf u understood the code then plz.......UPVOTE...........Thnx in adv | 2 | 0 | ['Recursion', 'Python'] | 1 |
calculate-digit-sum-of-a-string | 📌Fastest java☕ solution. 0 ms💯 | fastest-java-solution-0-ms-by-saurabh_17-61is | ```\nclass Solution {\n public String digitSum(String s, int k) \n {\n while(s.length()>k)\n {\n StringBuilder u=new StringBuilde | saurabh_173 | NORMAL | 2022-04-28T19:22:40.732490+00:00 | 2022-04-28T19:22:40.732553+00:00 | 256 | false | ```\nclass Solution {\n public String digitSum(String s, int k) \n {\n while(s.length()>k)\n {\n StringBuilder u=new StringBuilder();\n for(int i=0;i<s.length();i+=k)\n {\n int n=0;\n for(int j=i;j<i+k && j<s.length(); j++)\n n+=s.charAt(j)-\'0\';\n u.append(n);\n }\n s=u.toString();\n }\n return s;\n }\n} | 2 | 0 | ['String', 'Java'] | 0 |
calculate-digit-sum-of-a-string | Python easy iterative solution for beginners | python-easy-iterative-solution-for-begin-g4dh | ```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n groups = [s[x:x+k] for x in range(0, len(s), k)]\n | elefant1805 | NORMAL | 2022-04-28T04:26:13.814740+00:00 | 2022-04-28T04:26:13.814783+00:00 | 327 | false | ```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n groups = [s[x:x+k] for x in range(0, len(s), k)]\n temp = ""\n for i in groups:\n dig = [int(y) for y in i]\n temp += str(sum(dig))\n s = temp\n return s | 2 | 0 | ['Python', 'Python3'] | 0 |
calculate-digit-sum-of-a-string | Java Solution - Easy to Understand | java-solution-easy-to-understand-by-tush-54wh | Here is my solution:\n\nclass Solution {\n public String digitSum(String s, int k) {\n \n while(s.length()>k){ /*If the length of the string | tushar30gaurab | NORMAL | 2022-04-21T19:13:14.641652+00:00 | 2022-04-22T18:02:10.270019+00:00 | 164 | false | Here is my solution:\n```\nclass Solution {\n public String digitSum(String s, int k) {\n \n while(s.length()>k){ /*If the length of the string is greater than k, repeat from step 1.*/\n \n String newstr = ""; /*for storing updated string*/\n \n for(int i=0; i<s.length(); i+=k){ // retrieving small parts of string in k equal parts\n\t\t\t\n int sum=0; // for finding "sum"\n\t\t\t\t\n String temp = s.substring(i,Math.min(i+k, s.length())); //for substring from ith to (i+k)th position\n\t\t\t\t\n for(int itr = 0; itr<temp.length(); itr++){\n sum += temp.charAt(itr) - \'0\';\n }\n \n newstr = newstr + "" + sum; // storing sum into new string\n }\n \n s = newstr; /*Updating original string with new string containing sum of digits*/\n }\n \n return s;\n }\n}\n```\nIf liked the approach. Pls **upvote** :)\nFeel free to ask any doubt..\nHappy Coding !! | 2 | 0 | ['Java'] | 0 |
calculate-digit-sum-of-a-string | Calculate Digit Sum of a String T.C. O(n), S.C. O(1). | calculate-digit-sum-of-a-string-tc-on-sc-cziq | \nclass Solution {\npublic:\n string digitSum(string s, int k) \n {\n while (s.size() > k) // Run the loop until given string s length is greater | shubhammishra115 | NORMAL | 2022-04-19T13:24:21.386389+00:00 | 2022-04-19T13:24:21.386429+00:00 | 400 | false | ```\nclass Solution {\npublic:\n string digitSum(string s, int k) \n {\n while (s.size() > k) // Run the loop until given string s length is greater than k otherwise return the string.\n {\n string temp = ""; // Temp variable to store the new string.\n for (int i = 0; i < s.size(); i++)\n {\n int sum = 0;\n int count = 0;\n while (i < s.size() && count < k) // Run the loop until count is less than k or iterator is less than the size of string.\n {\n sum += s[i++] - \'0\'; // Sum up the string value\n count++; // Increase the count \n }\n temp += to_string(sum); // Add the obtained sum to the temp variable.\n i--;\n }\n s = temp; // Update the value of main string.\n }\n return s; // Return the final string.\n }\n};\n\n// Hope it will help. :)\n``` | 2 | 0 | ['String', 'C', 'C++'] | 0 |
calculate-digit-sum-of-a-string | python | recursion | easy | python-recursion-easy-by-mamtadnr-wjyk | \nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n if len(s)<=k:\n return s\n def digitsm(s):\n sm=0\n | mamtadnr | NORMAL | 2022-04-17T16:33:46.542792+00:00 | 2022-04-17T16:33:46.542857+00:00 | 57 | false | ```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n if len(s)<=k:\n return s\n def digitsm(s):\n sm=0\n for i in range(len(s)):\n sm+=int(s[i])\n return sm\n string=\'\'\n for i in range(0,len(s),k):\n try:\n string+=str(digitsm(s[i:i+k]))\n except:\n string+=str(digitsm(s[i:]))\n if len(string)<=k:\n return string\n return self.digitSum(string,k)\n \n``` | 2 | 0 | [] | 0 |
calculate-digit-sum-of-a-string | JAVA (StringBuilder and String) Commented | java-stringbuilder-and-string-commented-c5kl6 | Using String :\nRuntime: 6 ms\nMemory Usage: 40.6 MB\n\nclass Solution {\n public String digitSum(String s, int k) {\n int len = s.length();\n | Srishti2002in | NORMAL | 2022-04-17T07:37:11.145538+00:00 | 2022-04-17T07:41:56.703058+00:00 | 171 | false | Using String :\nRuntime: 6 ms\nMemory Usage: 40.6 MB\n```\nclass Solution {\n public String digitSum(String s, int k) {\n int len = s.length();\n String ans = s; //making a copy of string s\n while(ans.length() > k) {\n String dummy = ""; // this will store the string after a round\n int i = 0;\n for(i = 0; i < ans.length(); i+=k) {\n int sum = 0;\n for(int j = 0; j < k && (j+i) < ans.length(); j++) {\n sum += ans.charAt(i+j)-\'0\';\n }\n dummy += sum+""; //adding the result to the string\n }\n ans = dummy; //adding modified value to the answer\n }\n return ans;\n }\n}\n```\n\nUsing StringBuilder :\nRuntime: 1 ms\nMemory Usage: 40.7 MB\n\n```\nclass Solution {\n public String digitSum(String s, int k) {\n StringBuilder ans = new StringBuilder(s);\n int len = s.length();\n while(ans.length() > k) {\n StringBuilder dummy = new StringBuilder();\n int i = 0;\n for(i = 0; i < ans.length(); i+=k) {\n int sum = 0;\n for(int j = 0; j < k && (j+i) < ans.length(); j++) {\n sum += ans.charAt(i+j)-\'0\';\n }\n dummy.append(sum+"");\n }\n ans = dummy;\n }\n return ans.toString();\n }\n}\n``` | 2 | 0 | ['String', 'Java'] | 0 |
calculate-digit-sum-of-a-string | javascript direct way 84ms | javascript-direct-way-84ms-by-henrychen2-3de9 | \nconst digitSum = (s, k) => {\n while (s.length > k) {\n let t = \'\'; // each round accumalate new string t\n for (let i = 0; i < s.length; i | henrychen222 | NORMAL | 2022-04-17T04:48:15.026682+00:00 | 2022-04-17T04:50:58.119475+00:00 | 251 | false | ```\nconst digitSum = (s, k) => {\n while (s.length > k) {\n let t = \'\'; // each round accumalate new string t\n for (let i = 0; i < s.length; i += k) {\n let sub = s.slice(i, i + k), sum = 0;\n for (const c of sub) sum += c - \'0\'; // sum of each digits\n t += sum; // rebuild new string with sum\n }\n s = t; // update new string to s\n }\n return s;\n};\n``` | 2 | 0 | ['String', 'JavaScript'] | 0 |
calculate-digit-sum-of-a-string | [C++] String problem | c-string-problem-by-animesh_roy-1n4i | \nclass Solution {\npublic:\n string digitSum(string s, int k) {\n while(s.length()>k){\n string temp="";\n int p=0, sum=0;\n | Animesh_Roy | NORMAL | 2022-04-17T04:19:54.632141+00:00 | 2022-04-17T04:19:54.632166+00:00 | 178 | false | ```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n while(s.length()>k){\n string temp="";\n int p=0, sum=0;\n for(int i=0; i<s.length(); i++){\n sum += s[i]-\'0\';\n p++;\n if(p==k){\n temp += to_string(sum);\n sum=0;\n p=0;\n }\n }\n if(p>0) temp += to_string(sum);\n s=temp;\n }\n return s;\n }\n};\n``` | 2 | 0 | ['String', 'C'] | 0 |
calculate-digit-sum-of-a-string | C++|| solution | c-solution-by-soujash_mandal-tv3m | \nclass Solution {\npublic:\n string digitSum(string s, int k) {\n \n \n \n while(s.size()>k)\n {\n string res= | soujash_mandal | NORMAL | 2022-04-17T04:01:31.415158+00:00 | 2022-04-17T04:01:31.415195+00:00 | 290 | false | ```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n \n \n \n while(s.size()>k)\n {\n string res="";\n int n=s.size();\n int i=0;\n while(i<n)\n {\n int c=0;\n string temp="";\n int count=0;\n while(i<n && c<k)\n {\n count+=s[i]-\'0\';\n c++;\n i++;\n }\n string str=to_string(count);\n res+=str;\n }\n \n s=res;\n }\n return s;\n }\n};\n``` | 2 | 0 | [] | 1 |
calculate-digit-sum-of-a-string | Calculate Digit Sum of a String (Finally done it on my own) | calculate-digit-sum-of-a-string-finally-ggucx | IntuitionApproachComplexity
Time complexity:
(n log n)
Space complexity:
O(n)Code | Vinil07 | NORMAL | 2025-03-25T06:39:39.195311+00:00 | 2025-03-25T06:39:39.195311+00:00 | 45 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
(n log n)
****
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n)
# Code
```cpp []
class Solution {
public:
string digitSum(string s, int k) {
while(s.size()>k)
{
string temp="";
int sum=0;
for(int i=0;i<s.size();i++)
{
sum+=s[i]-'0';
if((i+1)%k==0)
{
temp+=to_string(sum);
sum=0;
}
}
if(s.size()%k!=0)
{
temp+=to_string(sum);
}
s=temp;
}
return s;
}
};
``` | 1 | 0 | ['String', 'Simulation', 'C++'] | 0 |
calculate-digit-sum-of-a-string | [C#] | O(N) | 0 ms | 100% | Best Solution | c-on-0-ms-100-best-solution-by-sovokan-4dvz | Approach
First, let's loop our algorithm until s.Length > k. (Step 3)
Use StringBuilder because it's faster than string concatenation. For performance, you can | SoVoKaN | NORMAL | 2025-01-31T03:48:55.813969+00:00 | 2025-01-31T03:48:55.813969+00:00 | 41 | false | # Approach
- First, let's loop our algorithm until `s.Length > k`. (Step 3)
- Use `StringBuilder` because it's faster than string concatenation. For performance, you can set Capacity.
- First cycle - required to save the position after the group sum calculation.
- The variables `sum` and `j` are declared in the first cycle. (`j` is declared outside the second cycle because it's value is passed to `i` after the cycle)
- The second cycle - required to calculate the sum of numbers in the group `k`. (`'0'` in ASCII table = 48)
- Since the last group can be smaller than `k`, check that `j` is smaller than the `s.Length`.
- Add `sum` to `StringBuilder` and assign the position `j` to `i`.
- Then assign your string from `StringBuilder` to `s`.
- And finally return `s`.
# Complexity
- Time complexity: **O(N)**
- Space complexity: **O(1)**
# Code
```csharp []
public class Solution
{
public string DigitSum(string s, int k)
{
while (s.Length > k)
{
StringBuilder builder = new StringBuilder(20);
for (int i = 0; i < s.Length;)
{
int sum = 0, j = i;
for (; j < s.Length && j < i + k; j++)
{
sum += s[j] - 48;
}
builder.Append(sum);
i = j;
}
s = builder.ToString();
}
return s;
}
}
```
---
Thank you for reading my post. Please upvote it! ✔️
--- | 1 | 0 | ['Array', 'Two Pointers', 'String', 'C#'] | 0 |
calculate-digit-sum-of-a-string | ✅✅ Python easy 3 Liner | Beats 100% | 0ms | Sum of Digits List Comprehension ✅✅ | python-easy-3-liner-beats-100-0ms-sum-of-3gzn | Code | nicostoehr | NORMAL | 2025-01-30T18:01:53.810436+00:00 | 2025-01-30T18:01:53.810436+00:00 | 85 | false | # Code
```python3 []
class Solution:
def digitSum(self, s: str, k: int) -> str:
def sod(w): return str(sum([int(x) for x in w]))
while len(s) > k: s = "".join(([sod(s[i*k:i*k+k]) for i in range(ceil(len(s)/k))]))
return s
``` | 1 | 0 | ['Python3'] | 0 |
calculate-digit-sum-of-a-string | 100% easy solution | 100-easy-solution-by-tashu002-q7j7 | IntuitionApproachComplexity
Time complexity:O(n)
Space complexity:O(1)
Code | Tashu002 | NORMAL | 2025-01-01T05:52:19.077955+00:00 | 2025-01-01T05:52:19.077955+00:00 | 125 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
string digitSum(string s, int k) {
while(s.length() > k){
string temp = "";
for(int i = 0; i < s.length(); i += k){
int num = 0;
for(int j = i; j < i+ k && j < s.length(); j++){
num += (s[j] - '0');
}
// string temp1 = str(num);
temp += to_string(num); // int to string
}
s = temp;
}
return s;
}
};
``` | 1 | 0 | ['Two Pointers', 'C++'] | 0 |
calculate-digit-sum-of-a-string | leetcodedaybyday - Beats 100% with C++ and Beats 100% with Python3 | leetcodedaybyday-beats-100-with-c-and-be-zi45 | IntuitionThe problem involves repeatedly compressing a string by summing groups of k consecutive characters. The goal is to reduce the string until its length i | tuanlong1106 | NORMAL | 2024-12-27T06:51:27.531750+00:00 | 2024-12-27T06:51:27.531750+00:00 | 85 | false | # Intuition
The problem involves repeatedly compressing a string by summing groups of `k` consecutive characters. The goal is to reduce the string until its length is less than or equal to `k`. This iterative process of summing digits helps in understanding and implementing a loop-based solution.
# Approach
1. **Digit Sum Helper**:
- Define a helper function to calculate the sum of digits for a given substring. In Python, this can be done using `sum(int(char) for char in substring)`.
2. **Iterative Compression**:
- While the string's length exceeds `k`, process the string:
- Divide the string into groups of `k` characters.
- For each group, compute the sum of its digits and convert the result back to a string.
- Concatenate these results to form the new compressed string.
- Repeat the process until the string length is less than or equal to `k`.
3. **Output**:
- Return the final compressed string.
# Complexity
- **Time Complexity**:
- Each iteration processes the string by summing digits, which takes \(O(n)\), where \(n\) is the length of the current string.
- In the worst case, the length of the string is halved in each iteration, leading to \(O(n \log(n))\).
- **Space Complexity**:
- In Python, temporary strings and substrings take \(O(n)\) space in total. For C++, string manipulations also require similar temporary space, resulting in \(O(n)\).
---
# Code
```cpp []
class Solution {
public:
int sum(string& s){
int n = s.size();
int ans = 0;
for (int i = 0; i < n; i++){
int dig = s[i] - '0';
ans += dig;
}
return ans;
}
string digitSum(string s, int k) {
while (s.size() > k){
string ans = "";
int n = s.size();
for (int i = 0; i < n; i += k){
string str = s.substr(i, min(k, n - i));
int res = sum(str);
ans += to_string(res);
}
s = ans;
}
return s;
}
};
```
```python3 []
class Solution:
def digitSum(self, s: str, k: int) -> str:
def digit(substring: str) -> int:
return sum(int(char) for char in substring)
while len(s) > k:
ans = ""
for i in range(0, len(s), k):
substring = s[i : i + k]
res = digit(substring)
ans += str(res)
s = ans
return s
```
| 1 | 0 | ['C++', 'Python3'] | 0 |
calculate-digit-sum-of-a-string | pathetic code but 100% beats and understandable | pathetic-code-but-100-beats-and-understa-079c | helper function, sums the group
helper function convert does 1 roundCode | pitcherpunchst | NORMAL | 2024-12-22T10:44:19.769574+00:00 | 2024-12-22T10:44:19.769574+00:00 | 39 | false | helper function, sums the group
helper function convert does 1 round
# Code
```cpp []
class Solution
{
public:
string sum(string st)
{
int s = 0;
for(char c : st)
s+= c-'0';
return to_string(s);
}
string convert(string s, int k)
{
vector<string> groups;
while(s.size()>=k)
{
groups.push_back(s.substr(0, k));
s.erase(s.begin(),s.begin()+k);
}
if(s.size()>0)
groups.push_back(s);
string ans;
for(string num : groups)
{
ans+=sum(num);
}
return ans;
}
string digitSum(string s, int k)
{
while(s.size()>k)
s = convert(s,k);
return s;
}
};
``` | 1 | 0 | ['C++'] | 0 |
calculate-digit-sum-of-a-string | Swift solution 1 while 1 for 1 if | swift-solution-1-while-1-for-1-if-by-ver-fus0 | # Intuition \n\n\n\n\n\n# Complexity\n- Time complexity: O(n)\n\n\n- Space complexity: O(n)\n\n\n# Code\nswift []\nclass Solution {\n func digitSum(_ s: St | vert | NORMAL | 2024-11-19T21:04:20.630548+00:00 | 2024-11-19T21:04:20.630584+00:00 | 6 | false | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```swift []\nclass Solution {\n func digitSum(_ s: String, _ k: Int) -> String {\n var res = Array(s) \n\n while res.count > k {\n var newStr = ""\n var currSum = 0\n\n for i in 0..<res.count {\n currSum += res[i].wholeNumberValue ?? 0\n\n if (i + 1) % k == 0 || i == res.count - 1 {\n newStr.append("\\(currSum)")\n currSum = 0\n }\n }\n res = Array(newStr)\n }\n return String(res)\n }\n}\n``` | 1 | 0 | ['Swift'] | 0 |
calculate-digit-sum-of-a-string | chal finally did on own like fully own no bugs :D but must try hard bahut hai krna | chal-finally-did-on-own-like-fully-own-n-p014 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | yesyesem | NORMAL | 2024-11-18T13:48:22.161558+00:00 | 2024-11-18T13:48:22.161595+00:00 | 33 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n\n string temp=s;\n int c=0;\n int num=0;\n string calc="";\n\n while(temp.size()>k)\n {\n calc="";\n num=0;\n c=0;\n\n for(int i=0;i<temp.size();i++)\n {\n num+=temp[i]-\'0\';\n c++;\n\n if(c==k || i==temp.size()-1)\n {\n c=0;\n calc+=to_string(num);\n num=0;\n\n }\n }\n temp=calc;\n\n\n }\n \n return temp;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
calculate-digit-sum-of-a-string | Likha tha logic still kuch bugs the wo fix krne mein help lagi will try tm again :D | likha-tha-logic-still-kuch-bugs-the-wo-f-blu5 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | yesyesem | NORMAL | 2024-11-17T19:05:45.683088+00:00 | 2024-11-17T19:05:45.683120+00:00 | 22 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n \n string temp=s;\n \n int num=0;\n string calc="";\n int c=0;\n\n while(temp.size()>k)\n {\n calc="";\n num=0;\n c=0;\n for(int i=0;i<temp.size();i++)\n {\n\n num+=temp[i]-\'0\';\n c++;\n\n if(c==k||i==temp.size()-1)\n {\n calc+=to_string(num);\n num=0;\n c=0;\n }\n \n \n \n\n \n }\n\n \n\n temp=calc;\n\n }\n return temp;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
calculate-digit-sum-of-a-string | Easy Java Solution ( 0 ms time complexity) | easy-java-solution-0-ms-time-complexity-0bd87 | Intuition\ndivide, replace , merge\n\n# Approach\neasy\n\n# Complexity\n- Time complexity:\n0ms\n\n\n\n# Code\njava []\nclass Solution {\n public String digi | Vaishnavi7m | NORMAL | 2024-09-21T19:57:56.911344+00:00 | 2024-09-21T19:57:56.911374+00:00 | 51 | false | # Intuition\n**divide, replace , merge**\n\n# Approach\neasy\n\n# Complexity\n*- Time complexity:\n0ms*\n\n\n\n# Code\n```java []\nclass Solution {\n public String digitSum(String s, int k) {\n \n while(s.length()>k)\n s = makeParts(s,k);\n return s;\n }\n\n public String makeParts(String s,int k){\n int n = s.length();\n StringBuilder sb = new StringBuilder();\n int i = 0;\n while(i<n){\n int cnt = 0;\n int sum = 0;\n while(cnt<k && i<n){\n sum+=s.charAt(i)-\'0\';\n i++;\n cnt++;\n }\n sb.append(sum);\n }\n return sb.toString();\n }\n\n \n}\n``` | 1 | 0 | ['String', 'Simulation', 'Java'] | 0 |
calculate-digit-sum-of-a-string | without using any inbuilt method,pure logic | without-using-any-inbuilt-methodpure-log-c4pt | Code\njavascript []\n/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nvar digitSum = function (s, k) {\n\n function rec(s) {\n | ali-miyan | NORMAL | 2024-09-21T00:59:56.482960+00:00 | 2024-09-21T00:59:56.482985+00:00 | 19 | false | # Code\n```javascript []\n/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nvar digitSum = function (s, k) {\n\n function rec(s) {\n if (s.length <= k) return s\n\n let str = \'\';\n\n\n for (let i = 0; i < s.length; i += k) {\n let str2 = 0\n for (let j = i; j < i + k && j < s.length; j++) {\n str2 += Number(s[j]);\n }\n str += str2.toString()\n }\n console.log(str.length !== k)\n\n if(str.length !== k){\n return rec(str)\n }else{\n return str\n }\n\n\n }\n\n return rec(s)\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
calculate-digit-sum-of-a-string | C# nothing special, code explain itself | c-nothing-special-code-explain-itself-by-r2jj | Code\ncsharp []\npublic class Solution {\n public string DigitSum(string s, int k) {\n var sb = new StringBuilder();\n while(s.Length > k){\n | nzspider | NORMAL | 2024-09-06T06:56:40.776276+00:00 | 2024-09-06T06:56:40.776313+00:00 | 12 | false | # Code\n```csharp []\npublic class Solution {\n public string DigitSum(string s, int k) {\n var sb = new StringBuilder();\n while(s.Length > k){\n var lists = SplitStringByLength(s, k);\n foreach(var str in lists){\n var sum = str.Select(c=>c-\'0\').Sum();\n sb.Append(sum.ToString());\n }\n s = sb.ToString();\n sb.Clear();\n }\n return s;\n }\n\n public IEnumerable<string> SplitStringByLength(string str, int length)\n {\n for (int i = 0; i < str.Length; i += length)\n {\n yield return str.Substring(i, Math.Min(length, str.Length - i));\n }\n }\n}\n``` | 1 | 0 | ['C#'] | 0 |
calculate-digit-sum-of-a-string | 🦚 Simple Approach || Easy Code !! || Simple & Concise Code || C++ Code Reference ! | simple-approach-easy-code-simple-concise-ctjr | Intuition\n- Intuition Is On Sleep Mode.\n# Code\ncpp [There You Go !]\n\n string digitSum(string s, int k) {\n \n int sum=0;\n string t=""; | Amanzm00 | NORMAL | 2024-09-01T03:52:16.865672+00:00 | 2024-09-01T03:52:16.865692+00:00 | 64 | false | # Intuition\n- Intuition Is On Sleep Mode.\n# Code\n```cpp [There You Go !]\n\n string digitSum(string s, int k) {\n \n int sum=0;\n string t=""; \n\n while(s.length()>k)\n {\n for(int i=0;i<s.length();i++)\n {\n sum += (s[i]-\'0\');\n\n if((i+1)%k ==0 || i==s.length()-1)\n t+=to_string(sum), sum=0;\n }\n s=t,t="";\n\n }\n\n return s;\n }\n\n``` | 1 | 0 | ['String', 'Simulation', 'C++'] | 0 |
calculate-digit-sum-of-a-string | Simple java code | simple-java-code-by-arobh-exrt | \n# Complexity\n- \n\n# Code\n\nclass Solution {\n public String sumD(String s,int k){\n int n=s.length();\n String s2="";\n for(int i=0 | Arobh | NORMAL | 2023-12-31T02:29:38.202760+00:00 | 2023-12-31T02:29:38.202788+00:00 | 17 | false | \n# Complexity\n- \n\n# Code\n```\nclass Solution {\n public String sumD(String s,int k){\n int n=s.length();\n String s2="";\n for(int i=0;i<n;i=i+k){\n int sum=0;\n int flag=0;\n for(int j=i;j<i+k&&j<n;j++){\n int key=(int)(s.charAt(j)-\'0\');\n sum+=key;\n flag=1;\n }\n if(flag==1){\n s2=s2+sum;\n }\n else{\n for(int j=i;j<n;j++){\n int key=(int)(s.charAt(j)-\'0\');\n sum+=key;\n }\n s2=s2+sum;\n break;\n }\n\n }\n return s2;\n }\n public String digitSum(String s, int k) {\n if(s.length()<=k){\n return s;\n }\n String s2=sumD(s,k);\n while(s2.length()>k){\n s2=sumD(s2,k);\n }\n return s2;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
calculate-digit-sum-of-a-string | EASY CPP Solution | | Beats 100% in Runtime | | Beginner Friendly | easy-cpp-solution-beats-100-in-runtime-b-34uw | \n\n\n# Code\n\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n string ans = s;\n while(ans.length() > k){\n string | Sumit_Soni_999 | NORMAL | 2023-09-21T18:54:13.250716+00:00 | 2023-09-21T18:54:13.250745+00:00 | 55 | false | \n\n\n# Code\n```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n string ans = s;\n while(ans.length() > k){\n string tmp = "";\n int num = 0, cnt=0;\n for(int i=0; i<ans.length(); i++){\n num += ans[i] - \'0\';\n cnt++;\n if(i != 0 && cnt == k || i == ans.length()-1){\n tmp += to_string(num);\n num = cnt = 0;\n }\n }\n ans = tmp;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
calculate-digit-sum-of-a-string | C++ Easy Solution || Beginner's Solution || Vector✅✅ | c-easy-solution-beginners-solution-vecto-gpj5 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Manisha_jha658 | NORMAL | 2023-08-15T20:56:09.051861+00:00 | 2023-08-15T20:56:09.051879+00:00 | 705 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n vector<int> ans;\n int num=0;\n\n//Till the size of string is greater, while loop will work.\n while(s.size()>k){\n for(int i=0;i<s.size();i++){\n num=0;\n for(int j=0;j<k;j++){\n//while increasing j, always check whether i is less than the actual size.\n if(i<s.size()) \n num=num+s[i]+\'0\'-96;\n//If s[i]=1 then to change it in integer add \'0\' it become 97 thus sub 96.\n i++;\n }\n i--;\n ans.push_back(num);\n }\n s.clear(); //clear previous string\n for(int i=0;i<ans.size();i++){\n s=s+to_string(ans[i]); \n//change each number to string for concatenation \n }\n \n ans.clear();\n }\n return s;\n \n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
calculate-digit-sum-of-a-string | Golang: recursion - runtime 0 ms, Beats 100% | golang-recursion-runtime-0-ms-beats-100-vta97 | \n# Code\n\nfunc digitSum(s string, k int) string {\n if len(s) <= k { return s }\n result := split(s, k)\n return digitSum(stringCount(result), k)\n}\ | 9bany | NORMAL | 2023-06-23T09:15:57.787112+00:00 | 2023-06-23T09:16:48.382896+00:00 | 171 | false | \n# Code\n```\nfunc digitSum(s string, k int) string {\n if len(s) <= k { return s }\n result := split(s, k)\n return digitSum(stringCount(result), k)\n}\n\nfunc stringCount(strs []string) (result string) {\n for _, elements := range strs {\n sum := 0 \n for _, item := range elements {\n i, _ := strconv.Atoi(string(item))\n sum += i\n }\n result += fmt.Sprint(sum)\n }\n return\n}\n\nfunc split(s string, k int) (result []string) {\n if len(s) <= k { return []string{s} }\n result = append(result, s[:k])\n result = append(result, split(s[k:], k)...)\n return\n}\n``` | 1 | 0 | ['Go'] | 0 |
calculate-digit-sum-of-a-string | Ruby Solution. Easy to understand | ruby-solution-easy-to-understand-by-gusw-jsa1 | \n# @param {String} s\n# @param {Integer} k\n# @return {String}\ndef digit_sum(s, k)\n while s.size > k\n arr = []\n i = 0\n while i < s | guswhitten | NORMAL | 2023-01-17T21:14:45.040301+00:00 | 2023-01-17T21:14:45.040329+00:00 | 25 | false | ```\n# @param {String} s\n# @param {Integer} k\n# @return {String}\ndef digit_sum(s, k)\n while s.size > k\n arr = []\n i = 0\n while i < s.size\n sum = 0\n s[i...(i + k)].each_char { |c| sum += c.to_i }\n arr.push(sum.to_s)\n i += k\n end\n s.replace(arr.join)\n end\n \n s\nend\n``` | 1 | 0 | ['Ruby'] | 0 |
calculate-digit-sum-of-a-string | Iterate and Sum | iterate-and-sum-by-prashantunity-9nvk | \n# Code\n\npublic class Solution \n{\n public string DigitSum(string s, int k)\n {\n while(s.Length>k)\n {\n var sb = new String | PrashantUnity | NORMAL | 2022-12-21T11:47:32.427578+00:00 | 2022-12-21T11:47:32.427616+00:00 | 463 | false | \n# Code\n```\npublic class Solution \n{\n public string DigitSum(string s, int k)\n {\n while(s.Length>k)\n {\n var sb = new StringBuilder();\n int j=k;\n int ans=0;\n for(var i=0;i<s.Length;i++)\n {\n ans+=Convert.ToInt32(s[i].ToString());\n if(i==j-1)\n {\n sb.Append(ans.ToString());\n ans=0;\n j+=k;\n }\n }\n if(j>s.Length && s.Length%k!=0)\n {\n sb.Append(ans.ToString());\n ans=0;\n j+=k;\n }\n s=sb.ToString();\n }\n return s;\n }\n}\n``` | 1 | 0 | ['C#'] | 0 |
calculate-digit-sum-of-a-string | C# | c-by-neildeng0705-4cuv | \n\npublic class Solution \n{\n public string DigitSum(string s, int k) \n {\n while(s.Length > k)\n {\n var chunks = s.Select((c | neildeng0705 | NORMAL | 2022-10-05T18:02:39.451679+00:00 | 2022-10-05T18:02:39.451709+00:00 | 112 | false | \n```\npublic class Solution \n{\n public string DigitSum(string s, int k) \n {\n while(s.Length > k)\n {\n var chunks = s.Select((c, index) => new {c, index})\n .GroupBy(x => x.index/k)\n .Select(group => group.Select(elem => elem.c))\n .Select(chars => new string(chars.ToArray()));\n s = string.Empty;\n foreach(string str in chunks)\n {\n s = s + str.Sum(c => c - \'0\').ToString();\n }\n }\n\n return s; \n }\n}\n``` | 1 | 0 | ['C#'] | 0 |
calculate-digit-sum-of-a-string | Python simple solution both recursive and iterative | python-simple-solution-both-recursive-an-euim | Recursive:\n\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n def str_sum(s):\n return str(sum([int(i) for i in s]))\n\n | Mark_computer | NORMAL | 2022-09-13T19:00:53.169534+00:00 | 2022-09-13T19:01:13.550011+00:00 | 215 | false | ***Recursive:***\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n def str_sum(s):\n return str(sum([int(i) for i in s]))\n\n if len(s) <= k:\n return s\n tmp = []\n for i in range(0, len(s), k):\n tmp.append(str_sum(s[i:i + k]))\n s = \'\'.join(tmp)\n return self.digitSum(s, k)\n```\n\n***Iterative:***\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n def str_sum(s):\n return str(sum([int(i) for i in s]))\n\n while len(s) > k:\n tmp = []\n for i in range(0, len(s), k):\n tmp.append(str_sum(s[i:i + k]))\n s = \'\'.join(tmp)\n return s\n``` | 1 | 0 | ['Recursion', 'Iterator', 'Python', 'Python3'] | 0 |
calculate-digit-sum-of-a-string | [ JAVA ] --> 1ms Runtime easy and elegant Solution | java-1ms-runtime-easy-and-elegant-soluti-fvo4 | \nint n=0,sum=0;\nStringBuilder ss=new StringBuilder(s);\nStringBuilder sk=new StringBuilder();\nwhile(ss.length()>k) {\n\tfor (int i = 0; i <= ss.length() - 1; | bgautam1254 | NORMAL | 2022-09-09T07:17:41.344238+00:00 | 2022-09-09T07:17:41.344277+00:00 | 303 | false | ```\nint n=0,sum=0;\nStringBuilder ss=new StringBuilder(s);\nStringBuilder sk=new StringBuilder();\nwhile(ss.length()>k) {\n\tfor (int i = 0; i <= ss.length() - 1; i++) {\n\t\tsum += ss.charAt(i) - \'0\';\n\t\tn++;\n\t\tif (n == k || i == ss.length() - 1) {\n\t\t\tsk.append(sum);\n\t\t\tn = 0;\n\t\t\tsum=0;\n\t\t\tif (i == ss.length() - 1) {\n\t\t\t\tss = new StringBuilder(sk);\n\t\t\t\tsk = new StringBuilder();\n\t\t\t}\n\t\t}\n\t}\n}\nreturn String.valueOf(ss);\n\n```\n**If you have any question, feel free to ask. If you like the solution or the explanation, Please UPVOTE !** | 1 | 0 | ['String', 'Java'] | 0 |
calculate-digit-sum-of-a-string | Java Solution || Thinking Recursively || easy to understand | java-solution-thinking-recursively-easy-9gqqi | \nclass Solution {\n public String digitSum(String s, int k) {\n if (s.length() <= k) {\n return s;\n }\n int i = 0;\n | beastfake8 | NORMAL | 2022-08-26T14:33:02.294867+00:00 | 2022-08-26T14:33:02.294899+00:00 | 163 | false | ```\nclass Solution {\n public String digitSum(String s, int k) {\n if (s.length() <= k) {\n return s;\n }\n int i = 0;\n String help = "";\n for (i = 0; i < s.length() - k; i += k) {\n String str = s.substring(i, i+k);\n int n = 0;\n for (char c : str.toCharArray()) {\n n += Character.getNumericValue(c);\n }\n help += n;\n }\n if (i != s.length()) {\n String str = s.substring(i);\n int n = 0;\n for (char c : str.toCharArray()) {\n n += Character.getNumericValue(c);\n }\n help += n;\n }\n return digitSum(help, k);\n }\n}\n``` | 1 | 0 | ['Recursion', 'Java'] | 0 |
calculate-digit-sum-of-a-string | simple recursion | simple-recursion-by-kj_shreyas-q2nl | \nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n self.res=""\n def recur(string):\n if len(string)<=k:\n | KJ_Shreyas | NORMAL | 2022-08-26T11:31:44.155837+00:00 | 2022-08-26T11:31:44.155862+00:00 | 196 | false | ```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n self.res=""\n def recur(string):\n if len(string)<=k:\n self.res=string\n return string\n i=0\n newString=""\n while i<len(string):\n a=string[i:i+k]\n sumn=None\n for j in a:\n if not sumn:\n sumn=int(j)\n continue\n sumn+=int(j)\n newString+=str(sumn)\n i+=k\n recur(newString)\n recur(s)\n return self.res\n``` | 1 | 0 | ['Python'] | 0 |
calculate-digit-sum-of-a-string | Easy and Faster than 100% solution in cpp | easy-and-faster-than-100-solution-in-cpp-3kv7 | class Solution {\npublic:\n string digitSum(string s, int k) {\n\t\n while(s.size()>k){\n string res="";\n for(int i=0;i<s.size();){\n | Harendra_Singh | NORMAL | 2022-08-25T21:13:34.777844+00:00 | 2022-08-25T21:13:34.777874+00:00 | 58 | false | class Solution {\npublic:\n string digitSum(string s, int k) {\n\t\n while(s.size()>k){\n string res="";\n for(int i=0;i<s.size();){\n int sum=0,j=i;\n for(;j<i+k and j<s.size();j++) sum+= (s[j]-\'0\');\n res+= to_string(sum);\n i=j;\n }\n s=res;\n }\n return s;\n }\n}; | 1 | 0 | [] | 0 |
calculate-digit-sum-of-a-string | [python] zip split, generator sum 5-liner (or 3 lines minified) - beats 100% | python-zip-split-generator-sum-5-liner-o-un6u | ```\nfrom itertools import chain\n\n\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n string = s\n tail = \'0\' * (k - 1)\n | perfontana | NORMAL | 2022-08-25T20:40:24.410698+00:00 | 2022-08-25T21:08:25.264180+00:00 | 208 | false | ```\nfrom itertools import chain\n\n\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n string = s\n tail = \'0\' * (k - 1)\n while len(string) > k:\n parts = list(\n zip(\n *(\n [iter(\n chain(string, tail)\n )] * k\n )\n )\n )\n string = \'\'.join(\n str(\n sum(\n int(number) for number in part\n )\n ) for part in parts\n )\n return string\n\t\t\n\t\t# ...or packed into (almost) one-liner\n\t\t#while len(s) > k:\n # s = \'\'.join(str(sum(int(number) for number in part)) for part in zip(*([iter(chain(s, \'0\' * (k - 1)))] * k)))\n #return s | 1 | 0 | ['String', 'Iterator', 'Python'] | 1 |
calculate-digit-sum-of-a-string | Easy to understand || C++ || Faster | easy-to-understand-c-faster-by-thirt13n-akgp | \nclass Solution {\npublic:\n int toint(string x){\n int I=0;\n for(int i=0; i<x.size(); i++)\n I+=x[i]-48;\n return I;\n | thirt13n | NORMAL | 2022-08-19T16:03:43.167343+00:00 | 2022-08-19T16:03:43.167376+00:00 | 205 | false | ```\nclass Solution {\npublic:\n int toint(string x){\n int I=0;\n for(int i=0; i<x.size(); i++)\n I+=x[i]-48;\n return I;\n }\n string digitSum(string s, int k) {\n while(s.size()>k){\n string temp="", x="";\n for(int i=0; i<s.size();i++){\n if((i+1)%k==0){\n x+=s[i];\n temp+=to_string(toint(x));\n x="";\n }\n else\n x+=s[i];\n }\n if(x.size())\n temp+=to_string(toint(x));\n s=temp;\n }\n return s;\n }\n};\n// Please upvote if its helpful to you! \n``` | 1 | 0 | ['String', 'C'] | 0 |
calculate-digit-sum-of-a-string | JavaScript - Easy Approach while loop | javascript-easy-approach-while-loop-by-g-hn6j | \n/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nconst digitSum = (s, k) => {\n while (s.length > k) {\n const getSum = ar | gpambasana | NORMAL | 2022-08-15T10:21:02.707244+00:00 | 2022-08-15T10:21:02.707290+00:00 | 265 | false | ```\n/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nconst digitSum = (s, k) => {\n while (s.length > k) {\n const getSum = arr => arr.reduce((a, n) => parseInt(a) + parseInt(n), 0).toString();\n const parts = s.match(new RegExp(`.{1,${k}}`, `g`));\n s = parts.map(p => getSum(p.split(``))).join(``);\n }\n \n return s;\n}\n``` | 1 | 0 | ['JavaScript'] | 0 |
calculate-digit-sum-of-a-string | simple PYTHON solution || easy to understand | simple-python-solution-easy-to-understan-ci6k | This is the solution which can be understand easily\n\nhere i have iterated until I get the size less than or equal to k :\nfor every iteration the value of the | narendra_036 | NORMAL | 2022-08-06T15:02:50.878509+00:00 | 2022-08-06T15:02:50.878547+00:00 | 115 | false | This is the solution which can be understand easily\n\nhere i have iterated until I get the size less than or equal to k :\nfor every iteration the value of the string changes\nfinally you will get the answer ..\n\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \n while len(s)>k:\n \n s=[int(i) for i in s]\n x=""\n for i in range(0,len(s),k):\n x+=str(sum(s[i:i+k]))\n s=x\n return s\n```\n[https://github.com/Narendrakumarreddy-Kadiri](http://) | 1 | 0 | ['Python'] | 0 |
calculate-digit-sum-of-a-string | Python3 O(n+k) || O(n) Runtime: 52ms 41.96% || Memory: 13.0mb 70.32% | python3-onk-on-runtime-52ms-4196-memory-5i608 | Hope I didn\'t coded this in hardcore.\n\nclass Solution:\n# O(n+k) where n is the elements present in the string\n# and k is the number of steps\n# O(N) sp | arshergon | NORMAL | 2022-07-24T17:55:00.627399+00:00 | 2022-07-24T17:55:00.627440+00:00 | 170 | false | Hope I didn\'t coded this in hardcore.\n```\nclass Solution:\n# O(n+k) where n is the elements present in the string\n# and k is the number of steps\n# O(N) space\n# Runtime: 52ms 41.96% || Memory: 13.0mb 70.32%\n def digitSum(self, string: str, k: int) -> str:\n if not string:\n return string\n stringLength = len(string)\n k %= stringLength \n if stringLength == k or k == 0 or k == 1:\n return string\n\n return helper(string, k)\n\ndef helper(string, k):\n newStringList = list(string)\n newNum = 0\n tempList = list()\n for i in range(0, len(newStringList), k):\n newNum = sum(map(int, newStringList[i:k+i]))\n tempList += list(str(newNum))\n\n result = \'\'.join(tempList)\n if len(result) > k:\n return helper(result, k)\n return result\n``` | 1 | 0 | ['String', 'Python', 'Python3'] | 0 |
calculate-digit-sum-of-a-string | java solution | java-solution-by-mansishahh-arew | Iterative:\n\n\tclass Solution {\n public String digitSum(String s, int k) {\n if(s.length() <= k)\n return s;\n \n while(s.l | MansiShahh | NORMAL | 2022-06-21T04:23:35.551300+00:00 | 2022-07-18T05:23:16.791523+00:00 | 113 | false | Iterative:\n\n\tclass Solution {\n public String digitSum(String s, int k) {\n if(s.length() <= k)\n return s;\n \n while(s.length() > k){\n String temp = "";\n for(int i = 0; i < s.length(); i += k){\n int curSum = 0;\n for(int j = 0; j < k && (j + i) < s.length(); j++){\n curSum += s.charAt(i + j) - \'0\';\n }\n temp += curSum +"";\n }\n s = temp;\n }\n \n return s;\n }\n\t}\n\nRecursive:\n\n\tclass Solution {\n public String digitSum(String s, int k) {\n \n while(s.length() > k){\n s = roundTrip(s, k);\n }\n return s;\n }\n \n public String roundTrip(String s, int k){\n int i = 0, j = 0, currSum = 0;\n String ans = "";\n for(;i < s.length();){\n while(j < k && i < s.length()){\n currSum += s.charAt(i) - \'0\';\n i++;\n j++;\n }\n ans += currSum;\n j = 0; \n currSum = 0;\n }\n \n return ans;\n }\n\t} | 1 | 0 | ['Java'] | 0 |
calculate-digit-sum-of-a-string | C++ | Simulation (Iterative) | Time: O(len) | Auxiliary Space: O(len / k) | c-simulation-iterative-time-olen-auxilia-nuvk | \nclass Solution {\npublic:\n string digitSum(string s, int k) {\n while (s.length() > k) {\n string ret = "";\n for (int i = 0; | happylifewy | NORMAL | 2022-06-13T05:27:32.651441+00:00 | 2022-06-13T05:27:32.651490+00:00 | 74 | false | ```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n while (s.length() > k) {\n string ret = "";\n for (int i = 0; i < s.length(); i += k) {\n string sub = s.substr(i, k);\n int sum = 0;\n for (auto c: sub) {\n sum += c - \'0\';\n }\n ret += to_string(sum);\n }\n s = ret;\n }\n return s;\n }\n};\n``` | 1 | 0 | [] | 0 |
calculate-digit-sum-of-a-string | C naive solution- faster than 100%- explained | c-naive-solution-faster-than-100-explain-kxqd | \'\'\'\n\n\nchar * digitSum(char * s, int k){\n \n\t\t//base case\n\t\tif (strlen(s) <= k)\n\t\t\treturn s;\n\n\t\t//iterate through s using sPtr\n\t\tint j | InbarRofman | NORMAL | 2022-06-02T11:42:44.060460+00:00 | 2022-06-02T11:42:44.060488+00:00 | 93 | false | \'\'\'\n\n\nchar * digitSum(char * s, int k){\n \n\t\t//base case\n\t\tif (strlen(s) <= k)\n\t\t\treturn s;\n\n\t\t//iterate through s using sPtr\n\t\tint j = 0;\n\t\tchar *sPtr = s;\n\t\twhile (*sPtr != \'\\0\')\n\t\t{\n\t\t\tint sum = 0;\n\n\t\t\t//calculating the sum of groups of k\n\t\t\tfor (int i = 0; (i < k) && (*sPtr!=\'\\0\'); i++)\n\t\t\t{\n\t\t\t\tsum += *sPtr - \'0\';\n\t\t\t\tsPtr++;\n\t\t\t}\n\n\t\t\t//if sum is more than one digit, the sum is casted to a string and read in reverse\n\t\t\tif (sum > 9)\n\t\t\t{\n\t\t\t\tint i = 0;\n\t\t\t\tchar s1[k];\n\t\t\t\twhile (sum != 0)\n\t\t\t\t{\n\t\t\t\t\ts1[i++] = sum%10 + \'0\';\n\t\t\t\t\tsum /= 10;\n\t\t\t\t}\n\t\t\t\ti--;\n\t\t\t\tchar *ptr = s1 + i;\n\t\t\t\twhile (i >= 0)\n\t\t\t\t{\n\t\t\t\t\ts[j++] = s1[i--];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\telse\n\t\t\t\ts[j++] = sum + \'0\';\n\n\t\t}\n\t\ts[j] = \'\\0\';\n\n\t\t//recursive call for the new s\n\t\treturn digitSum(s, k);\n}\'\'\' | 1 | 0 | ['C'] | 0 |
calculate-digit-sum-of-a-string | Java | Easy to understand | java-easy-to-understand-by-lekh_nith-sw0g | \nclass Solution {\n public String digitSum(String s, int k) {\n while(s.length() > k){\n String str = "";\n for(int i=0; i<s.le | lekh_nith | NORMAL | 2022-05-27T05:28:58.861060+00:00 | 2022-05-27T05:28:58.861095+00:00 | 109 | false | ```\nclass Solution {\n public String digitSum(String s, int k) {\n while(s.length() > k){\n String str = "";\n for(int i=0; i<s.length(); i=i+k){\n int sum = 0;\n for(int j=i; j<s.length() && j<i+k ; j++)\n sum += Character.getNumericValue(s.charAt(j));\n str += String.valueOf(sum);\n }\n s = str;\n }\n return s;\n }\n}\n``` | 1 | 0 | ['Iterator', 'Java'] | 0 |
calculate-digit-sum-of-a-string | Simple Ruby solution with full explanation | simple-ruby-solution-with-full-explanati-clg8 | \ndef digit_sum(s, k)\n # so we will loop until string size is greater than k\n while s.size > k\n # blank string to store up the value\n z = \'\'\n | abir162 | NORMAL | 2022-05-23T07:47:57.319604+00:00 | 2022-05-23T07:47:57.319639+00:00 | 57 | false | ```\ndef digit_sum(s, k)\n # so we will loop until string size is greater than k\n while s.size > k\n # blank string to store up the value\n z = \'\'\n # we will slice upto k elements and pass it to the loop\n s.chars.each_slice(k) do |a|\n # we will sum up, turn it into a string and add with the z\n z += a.sum(&:to_i).to_s\n end\n # we will pass z to s thus it will loop again\n s = z\n end\n # return s when it is not greater than k\n s\nend\n``` | 1 | 0 | ['Ruby'] | 0 |
calculate-digit-sum-of-a-string | Python | Very easy simulation | python-very-easy-simulation-by-__asrar-l9ew | \nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \'\'\'\n The basic idea is create a list of substrings with specified size k | __Asrar | NORMAL | 2022-05-15T20:12:59.828191+00:00 | 2022-05-15T20:12:59.828217+00:00 | 115 | false | ```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \'\'\'\n The basic idea is create a list of substrings with specified size k\n then perform digit sum and create a new string keep repeating the scenerio\n untill the newly formed string size becomes less then k.\n \'\'\'\n while len(s) > k:\n numslst = []\n for i in range(0,len(s),k):\n numslst.append(s[i:i+k])\n \n temp = \'\'\n for num in numslst:\n digits = [int(i) for i in num] # calculating digit in form of list\n temp += str(sum(digits)) # calculating sum\n s = temp # making current string as required string\n return s\n``` | 1 | 0 | ['String', 'Python'] | 0 |
calculate-digit-sum-of-a-string | C++ 12 line solution with Recursion | c-12-line-solution-with-recursion-by-ros-6gnh | \n\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n if(s.size() <= k)\n return s;\n string digits;\n for(int | roshatron | NORMAL | 2022-05-08T16:41:31.433698+00:00 | 2022-05-08T16:41:31.433724+00:00 | 107 | false | \n```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n if(s.size() <= k)\n return s;\n string digits;\n for(int i = 0; i < s.size(); i += k){\n string window = s.substr(i,k);\n int sum = 0;\n for(char i : window){\n sum += i - \'0\'; \n }\n digits += to_string(sum);\n }\n return digitSum(digits,k);\n }\n};\n``` | 1 | 0 | ['Recursion', 'C'] | 0 |
calculate-digit-sum-of-a-string | Java Easy Understanding - 8ms Using Recursive | java-easy-understanding-8ms-using-recurs-2buy | \n//This Solution Can Be Improved By Memoization Technique\nclass Solution {\n public String digitSum(String s, int k) {\n int sum = 0;\n Strin | Anbu_Mozhi_S | NORMAL | 2022-04-30T06:30:49.404372+00:00 | 2022-04-30T06:30:49.404409+00:00 | 97 | false | ```\n//This Solution Can Be Improved By Memoization Technique\nclass Solution {\n public String digitSum(String s, int k) {\n int sum = 0;\n String str = "";\n //Check If The Summed Up String\'s Length Is Less Than K \n while(s.length()>k){\n //Recursive Function To Find The Summed Up String\n s = calculateRecurse(s, k);\n }\n return s;\n }\n \n public String calculateRecurse(String str, int k){\n int sum = 0;\n //Check If The String\'s Length Is Less/Equal To K\n //Stopping Condition For A Recursive Function\n if(str.length() <= k){\n for(int i=0; i<str.length(); i++){\n //Easiest Way To Convert A Char Value To Integer\n sum += str.charAt(i) - 48;\n }\n //Easiest Way To Convert A Integer To Char\n return sum + "";\n }\n //Recursive Flow Condition\n String s = str.substring(0,k);\n for(int i=0; i<k; i++){\n sum += str.charAt(i) - 48;\n }\n return (sum + "") + calculateRecurse(str.substring(k,str.length()), k);\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
calculate-digit-sum-of-a-string | Simple Python Solution | simple-python-solution-by-runchen-mr4p | \nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n strList = [s[i:i+k] for i in range(0, len(s), k)]\n | runchen | NORMAL | 2022-04-28T19:24:25.293617+00:00 | 2022-04-28T19:24:25.293654+00:00 | 119 | false | ```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n strList = [s[i:i+k] for i in range(0, len(s), k)]\n \n for idx, _s in enumerate(strList):\n strList[idx] = self.getSum(_s)\n s = "".join(strList)\n return s\n \n def getSum(self, s: str) -> str:\n return str(sum(map(int, list(s))))\n``` | 1 | 0 | ['Python'] | 0 |
calculate-digit-sum-of-a-string | PHP | simple | 100 mem beat | php-simple-100-mem-beat-by-stuu-bqg2 | \n```\nclass Solution\n{\n\n /\n * @param string $s\n * @param int $k\n \n * @return String\n /\n public function digitSum($s, $k)\n {\n | stuu | NORMAL | 2022-04-28T11:26:35.538660+00:00 | 2022-04-28T11:26:35.538691+00:00 | 49 | false | \n```\nclass Solution\n{\n\n /**\n * @param string $s\n * @param int $k\n *\n * @return String\n */\n public function digitSum($s, $k)\n {\n if(strlen($s) <= $k) return $s;\n $chunks = array_chunk(str_split($s), $k);\n\n $ds = \'\';\n foreach ($chunks as $chunk) {\n $ds .= array_sum($chunk);\n }\n\n return $this->digitSum($ds, $k);\n }\n} | 1 | 0 | ['PHP'] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.