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.
You can do it in linear time if use linear space too. Construct a hash table whose keys will be all a[i]-k and a[i]+k (k above and below each numebr in the array).
Walk through the table once; for each number, add to your answer the value for key a[i] in the lookup table, and then increment a[i]-k and a[i]+k's value in the lookup table.
This solution worked for me; it takes O(n) time and O(n) space.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Pairs
You are viewing a single comment's thread. Return to all comments →
You can do it in linear time if use linear space too. Construct a hash table whose keys will be all a[i]-k and a[i]+k (k above and below each numebr in the array).
Walk through the table once; for each number, add to your answer the value for key a[i] in the lookup table, and then increment a[i]-k and a[i]+k's value in the lookup table.
This solution worked for me; it takes O(n) time and O(n) space.