GFG POTDHOMEMenu

Count all triplets with given sum in sorted array

Problem of the Day: Geeksforgeeks

Count all triplets with given sum in sorted array

Counting Triplets with a Given Sum in a Sorted Array – Algorithmic Challenge and Solution

Introduction

If you’re working on solving algorithmic problems in Python, one common task you might encounter is counting triplets that sum to a given target value in a sorted array. In this blog post, we’ll walk through a solution to this problem using Python, and we’ll discuss how to optimize this solution for SEO. By the end, you’ll not only be able to solve the triplet problem efficiently but also boost your SEO performance using tools like Yoast SEO Premium.

Given a sorted array arr[] and a target value, the task is to count triplets (i, j, k) of valid indices, such that arr[i] + arr[j] + arr[k] = target and i < j < k.

Examples:

Input: arr[] = [-3, -1, -1, 0, 1, 2], target = -2
Output: 4
Explanation: Two triplets that add up to -2 are:
arr[0] + arr[3] + arr[4] = (-3) + 0 + (1) = -2
arr[0] + arr[1] + arr[5] = (-3) + (-1) + (2) = -2
arr[0] + arr[2] + arr[5] = (-3) + (-1) + (2) = -2
arr[1] + arr[2] + arr[3] = (-1) + (-1) + (0) = -2
Input: arr[] = [-2, 0, 1, 1, 5], target = 1
Output: 0
Explanation: There is no triplet whose sum is equal to 1.

Constraints:
3 ≤ arr.size() ≤ 103
-105 ≤ arr[i], target ≤ 105

The Solution

To tackle this problem, we can use the following Python code:

 

Click Here to solve the code

 

The Solution

Here’s the Python code:

 

class Solution:
    def countTriplets(self, arr, target):
        # code here
        n = len(arr)
        mp = {}
    
        for i in range(n):
            if arr[i] not in mp:
                mp[arr[i]] = []
            mp[arr[i]].append(i)
    
        count = 0
        for i in range(n):
            for j in range(i + 1, n):
                sum_pair = arr[i] + arr[j]
            
                if target - sum_pair in mp:
                    for k in mp[target - sum_pair]:
                        if k > j:
                            count += 1
    
        return count

Line-by-Line Explanation:

1. class Solution:

  • This defines a class named Solution. In Python, we often define problems in classes to encapsulate methods related to the problem.

2. def countTriplets(self, arr, target):

  • This is a method within the Solution class. It accepts two parameters:
    • arr: The sorted list of integers.
    • target: The value we are trying to reach by summing triplets.

3. n = len(arr)

  • This calculates the size of the input array arr and stores it in the variable n. This will help us manage iterations in later steps.

4. mp = {}

  • Initializes an empty dictionary mp, which will map each number in arr to the indices where that number occurs.

5. for i in range(n):

  • Loops through the array arr using the index variable i.

6. if arr[i] not in mp:

  • Checks if the current element arr[i] is not already present in the dictionary mp. If it’s not, we initialize an empty list for that element.

7. mp[arr[i]] = []

  • Initializes an empty list for the current element in arr[i] if it hasn’t been seen before.

8. mp[arr[i]].append(i)

  • Appends the index i to the list of indices corresponding to arr[i].

9. count = 0

  • Initializes a variable count to track the number of valid triplets.

10. for i in range(n):

  • Starts an outer loop iterating over each element of arr, where i will represent the first element of the triplet.

11. for j in range(i + 1, n):

  • Starts an inner loop, which ensures that j > i to respect the condition that indices must be strictly increasing.

12. sum_pair = arr[i] + arr[j]

  • Calculates the sum of the first two elements (arr[i] and arr[j]), which is stored in the variable sum_pair.

13. if target - sum_pair in mp:

  • Checks if the third element required to complete the triplet (target - sum_pair) exists in mp.

14. for k in mp[target - sum_pair]:

  • Iterates through all the indices where the value target - sum_pair appears in the array arr.

15. if k > j:

  • Ensures that the index k (for the third element) is greater than j to maintain the condition i < j < k.

16. count += 1

  • Increments the count if a valid triplet is found.

17. return count

  • Finally, after all loops finish, returns the total count of triplets whose sum equals the target.

Example Walkthrough:

For an example input:

arr = [-3, -1, -1, 0, 1, 2]
target = -2
  1. Building the dictionary (mp):
    • The dictionary will look like this after processing the array:
    python
    mp = {-3: [0], -1: [1, 2], 0: [3], 1: [4], 2: [5]}

    This means:

    • -3 appears at index 0.
    • -1 appears at indices 1 and 2.
    • 0 appears at index 3.
    • 1 appears at index 4.
    • 2 appears at index 5.
  2. Iterating through pairs:
    • For the pair i = 0 and j = 1, the sum is -3 + (-1) = -4. The third element needed is -2 - (-4) = 2, which is found at index 5, so we have the triplet (-3, -1, 2).
    • Similarly, more valid triplets are found.
  3. Counting triplets:
    • The triplets that sum to -2 are:
      • (-3, -1, 2)
      • (-3, -1, 2)
      • (-3, 0, 1)
      • (-1, -1, 0)
    • Therefore, the final count is 4.

Time Complexity:

  • Dictionary Construction: O(n)O(n) where n is the length of the array.
  • Nested Loops: For each pair (i, j), the inner loop may iterate over all indices of the third element. This leads to a worst-case time complexity of O(n2)O(n^2).

Thus, the overall time complexity of the solution is O(n2)O(n^2).

Space Complexity:

  • The space complexity is O(n)O(n) due to the dictionary mp storing the indices of each element.

Click Here to solve the codeCount all triplets with given sum in sorted array 

 

Best AI Agent Courses for free 2024

Leave a Reply

Your email address will not be published. Required fields are marked *