We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
O(N) c# solution that passes all test cases. Idea is, we iterate over each element. When we see an element, we keep a count of the number of tuples we have seen so far.
static long countTriplets(List<long> arr, long r)
{
long count = 0;
Dictionary<string, long> dic = new Dictionary<string, long>();
long tmpCount;
for (int i = 0; i < arr.Count; i++)
{
long num3 = arr[i];
string key = "";
if (num3 % r == 0)
{
long num2 = num3 / r;
long num1 = num2 / r;
if (i > 1)
{
key = $"{num1}.{num2}";
if (dic.TryGetValue(key, out tmpCount))
{
count += tmpCount;
}
}
if (i > 0)
{
if (dic.TryGetValue(num2.ToString(), out tmpCount))
{
key = $"{num2}.{num3}";
if (dic.TryGetValue(key, out long tmpCount2))
{
tmpCount2 += tmpCount;
}
else
{
tmpCount2 = tmpCount;
}
dic[key] = tmpCount2;
}
}
}
key = num3.ToString();
if (dic.TryGetValue(key, out tmpCount))
{
tmpCount++;
}
else
{
tmpCount = 1;
}
dic[key] = tmpCount;
}
return count;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Count Triplets
You are viewing a single comment's thread. Return to all comments →
O(N) c# solution that passes all test cases. Idea is, we iterate over each element. When we see an element, we keep a count of the number of tuples we have seen so far.