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.
Divisible Sum Pairs
Divisible Sum Pairs
+ 0 comments JavaScript
function divisibleSumPairs(n, k, ar) { let count = 0; for(let i = 0; i < n; i++) { let temp = ar[i]; for(let j = i + 1; j < n; j++) { let sum = temp + ar[j]; if(sum % k == 0) { count += 1; } } } return count; }
+ 0 comments CPP
Time:O (n)
Space:O (n)
// returns the valid pairs of indexes vector<vector<int>> getAllSolutions(vector<int>& nums, int total, int len) { unordered_map<int, vector<int>> map; vector<vector<int>> results; for (int i = 0; i < len; i++) { // Example --> 17 % 7 = 3, we need (7 - 3) = 4, then (17 + 4) % 7 = 0 int remain = nums[i] % total; int complement = (total - remain) % total; // check if complement exists if (map.find(complement) != map.end()) { for (int index : map[complement]) { results.push_back({index, i}); } } // push again even if complement is already in the map map[remain].push_back(i); } return results; } int divisibleSumPairs(int len, int total, vector<int> nums) { vector<vector<int>> V = getAllSolutions(nums, total, len); return V.size(); }
+ 0 comments C# code
int count = 0; for (int i = 0; i < ar.Count(); i++) { for (int j = i+1; j < ar.Count(); j++) { if (i < j && (ar[i] + ar[j])%k ==0) { count++; } } }
+ 0 comments One of the possible Golang solution
func divisibleSumPairs(n int32, k int32, ar []int32) int32 { var i, j, countOfDivisibleByK int32 for i = 0; i < n-1; i++ { for j = i + 1; j < n; j++ { if (ar[i]+ar[j])%k == 0 { countOfDivisibleByK++ } } } return countOfDivisibleByK }
+ 0 comments def divisibleSumPairs(n, k, ar): matches = 0 for i in range(n): matches += len([(x, ar[i]) for x in ar[i+1:] if (ar[i] + x) % k == 0]) return matches
Load more conversations
Sort 2274 Discussions, By:
Please Login in order to post a comment