Suppose we have a list of numbers called nums. We have to find the sum of every concatenation of every pair of numbers in nums. Here the pair (i, j) and pair (j, i) are considered different.
So, if the input is like nums = [5, 3], then the output will be 176, as We have the following concatenations: (nums[0] + nums[0]) = (5 concat 5) = 55, (nums[0] + nums[1]) = (5 concat 3) = 53, (nums[1] + nums[0]) = (3 concat 5) = 35, (nums[0] + nums[0]) = (3 concat 3) = 33, then the sum is 55 + 53 + 35 + 33 = 176
To solve this, we will follow these steps:
memo := a new map nums1 := nums temp := 0 c := sum of all elements in nums1 a := size of nums for i in range 0 to a, do if nums[i] is same as 0, then temp := temp + c otherwise, if nums[i] is present in memo, then temp := temp + memo[nums[i]] otherwise, b := 0 for j in range 0 to a, do b := b + integer of (nums[i] concatenate nums1[j]) memo[nums[i]] := b temp := temp + memo[nums[i]] return temp
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, nums): memo = {} nums1 = nums temp = 0 c = sum(nums1) a = len(nums) for i in range(a): if nums[i] == 0: temp += c else: if nums[i] in memo: temp += memo[nums[i]] else: b = 0 for j in range(a): b += int(str(nums[i]) + str(nums1[j])) memo[nums[i]] = b temp += memo[nums[i]] return temp ob = Solution() nums = [5, 3] print(ob.solve(nums))
Input
[5, 3]
Output
176