I took a practice CodeSignal exam and was able to pass 14/16 test cases for this problem. You are given a vector as input (list of ints) and the solution will be long long.
Originally I simply used a brute-force solution of two for loops and adding the current a[i] concat a[j] to a running total. However, I tried to optimize this by using memoization. I used a unordered_map of pairs to check if I already computed the (i,j) pair and if so, simply return the cached result. Even with my optimization, I still don't pass any additional test cases and receive a 14/16 result. What insight or optimizations am I missing?
I have found similar online problems, however their insight doesn't seem to be applicable to this specific problem.
Ex: Similar Problem
Question:
Given an array of positive integers a, your task is to calculate the sum of every possible concat(a[i], a[j]), where concat(a[i],a[j]) is the concatenation of the string representations of a[I] and a[j] respectively.
Ex:
a = [10,2]
sol = 1344
a[0],a[0] = 1010
a[0],a[1] = 102
a[1],a[0] = 210
a[1],a[1] = 22
sum of above = 1344
Code:
long long concat(int x, int y)
{
string str = to_string(x)+to_string(y);
return stoll(str);
}
long long calculateSum(vector<int> a)
{
unordered_map<pair<int,int>,long long, hash_pair> memo;
long long total = 0;
for(int i = 0; i < a.size(); i++)
{
for(int j = 0; j < a.size(); j++)
{
auto currPair = make_pair(a[i],a[j]);
auto got = memo.find(currPair);
//if it's a new combination
if(currPair == got.end())
{
long long res = concat(a[i],a[j]);
memo.insert(make_pair(currPair,res));
total += res;
}
//we've computed this result before
else
{
total += got->second;
}
}
}
return total;
}