Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 3, 2018 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/e0eb390890bbc44d90ee265bf5e3d9bf to your computer and use it in GitHub Desktop.
Save jianminchen/e0eb390890bbc44d90ee265bf5e3d9bf to your computer and use it in GitHub Desktop.
First quadruplet - pass all test cases.
def find_array_quadruplet(arr, s):
if len(arr) < 4:
return []
pair_dict = {}
# preprocess
for i in xrange(0, len(arr)):
for j in xrange(i+1, len(arr)):
pair_sum = arr[i] + arr[j]
if pair_sum not in pair_dict:
pair_dict[pair_sum] = []
# i < j
pair_dict[pair_sum].append((i, j))
# find
for key, indices in pair_dict.iteritems():
if s - key not in pair_dict:
continue
# s - key in dict
s_indices = pair_dict[s-key]
# two indices list
for (i, j) in indices:
for (k, r) in s_indices:
if i != k and i != r and j != k and j != r:
# we have found the result
res = [arr[i], arr[j], arr[k], arr[r]]
return sorted(res)
return []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment