I had this problem in one of my interview practices and had a problem getting this with a better time complexity other than O(N^2). At some level you'll have to visit each element in the list. I thought about using hash table but it would still have to conduct the hash table and populate it then do the calculation. Basically my solution was a nested for loop and I have my code included as well and it passed everything except time exception under 4 seconds.
My Code:
def concatenationsSum(a):
sum = 0
current_index_looking_at = 0
for i in a:
for x in a:
temp = str(i)+str(x)
sum += int(temp)
return sum
The problem description:
Given an array of positive integers a, your task is to calculate the sum
of every possible a[i] ∘ a[j], where a[i] ∘ a[j] is the concatenation
of the string representations of a[i] and a[j] respectively.
Example
For a = [10, 2], the output should be concatenationsSum(a) = 1344.
a[0] ∘ a[0] = 10 ∘ 10 = 1010,
a[0] ∘ a[1] = 10 ∘ 2 = 102,
a[1] ∘ a[0] = 2 ∘ 10 = 210,
a[1] ∘ a[1] = 2 ∘ 2 = 22.
So the sum is equal to 1010 + 102 + 210 + 22 = 1344.
For a = [8], the output should be concatenationsSum(a) = 88.
There is only one number in a, and a[0] ∘ a[0] = 8 ∘ 8 = 88, so the answer is 88.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer a
A non-empty array of positive integers.
Guaranteed constraints:
1 ≤ a.length ≤ 10^5,
1 ≤ a[i] ≤ 10^6.
[output] integer64
The sum of all a[i] ∘ a[j]s. It's guaranteed that the answer is less than 2^53.