Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.1 kB
2
Indexable
Never
def find_triplets_with_sum(arr, target_sum):
    triplets = []
    arr.sort()  # Step 1: Sort the array

    for i in range(len(arr) - 2):  # Step 2: Iterate through the array
        left = i + 1  # Initialize the second pointer
        right = len(arr) - 1  # Initialize the third pointer

        while left < right:  # Step 3: Move left and right pointers
            current_sum = arr[i] + arr[left] + arr[right]
            if current_sum == target_sum:
                triplets.append([arr[i], arr[left], arr[right]])
                left += 1
                right -= 1
                # Skip duplicate values
                while left < right and arr[left] == arr[left - 1]:
                    left += 1
                while left < right and arr[right] == arr[right + 1]:
                    right -= 1
            elif current_sum < target_sum:
                left += 1  # Move the left pointer to the right
            else:
                right -= 1  # Move the right pointer to the left

    return triplets

# Example
arr = [-1, 0, 1, 2, -1, -4]
target_sum = 0
triplets = find_triplets_with_sum(arr, target_sum)
triplets
Leave a Comment