Skip to content
Prev Previous commit
Next Next commit
updated the comments as suggested by community
Signed-off-by: Sunny Kumar <[email protected]>
  • Loading branch information
Sunny Kumar committed Nov 6, 2023
commit 02a3f16e386344b36fe852eb73d0d3275cc5b4c8
10 changes: 5 additions & 5 deletions data_structures/arrays/find_triplets_with_0_sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,28 +54,28 @@ def find_triplets_with_0_sum_hashing(arr: list) -> list:
output_arr = []

# Set the initial element as arr[i].
for i in range(len(arr) - 2):
for i, item in enumerate(arr[:-2]):
# to store second elements that can complement the final sum.
set_initialize = set()

# current sum needed for reaching the target sum
current_sum = target_sum - arr[i]

# Traverse the subarray arr[i+1:].
for j in range(i + 1, len(arr)):
for other_item in arr[i+1:]:
# required value for the second element
required_value = current_sum - arr[j]
required_value = current_sum - arr[other_item]

# Verify if the desired value exists in the set.
if required_value in set_initialize:
# finding triplet elements combination.
combination_array = sorted([arr[i], arr[j], required_value])
combination_array = sorted([arr[i], arr[other_item], required_value])
if combination_array not in output_arr:
output_arr.append(combination_array)

# Include the current element in the set
# for subsequent complement verification.
set_initialize.add(arr[j])
set_initialize.add(arr[other_item])

# Return all the triplet combinations.
return output_arr