Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created April 29, 2018 06:56
Show Gist options
  • Save jianminchen/54dc109ce24b2974bdc1c7622694a896 to your computer and use it in GitHub Desktop.
Save jianminchen/54dc109ce24b2974bdc1c7622694a896 to your computer and use it in GitHub Desktop.
4 sum - array quadruplet - facebook United kingdom intern - bravo idea to build two sum hashmap
Leetcode 4 sum
For example, given an input array with the elements of [1, 6, 3, 8, 4, 0, 2],
given 4 sum value 14, the ordered quadruplet with 14 in an ascending order can be [0, 2, 4, 8].
thirdId = 0
allSums is empty
thirdId = 1
allSums is empty
thirdId = 2
allSums contain sum arr[0] + arr[1]
thirdId = 3
allSums contain arr[0] + arr[1], arr[0] + arr[2], arr[1] + arr[2]
thirdId = 4
given array, find quadruplet to have a sum matching given value
unordered_max <int, pair <int, int> > allSums;
i:
allSums will contain arr[j] + arr[k] for all (j < i && j < k < i )
HashMap.count(x) -> 0 if x is absent
non-zero otherwise
for (int thirdId = 0; thirdId < n; thirdId++) {
for (int fourthId = thirdId + 1; fourthId < n; fourthId++) {
int currSum = arr[thirdId] + arr[fouthId];
if (allSums.count(sum - currSum)) {
vector <int> ansIds(4);
ansIds[0] = allSums[sum - currSum].first; // ? key value - related to index third
ansIds[1] = allSums[sum - currSum].second;
ansIds[2] = thirdId;
ansIds[3] = fourthId;
return ansIds;
}
}
for (int firstId = 0; firstId < thirdId; firstId++) {
allSums[firstId + thirdId] = make_pair(firstId, thirdId);
}
}
return NULL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment