Program to check number of triplets from an array whose sum is less than target or not Python

Given a list of numbers and a target value, we need to find the count of triplets (i < j < k) where the sum nums[i] + nums[j] + nums[k] is less than the target.

For example, with nums = [−2, 6, 4, 3, 8] and target = 12, we have 5 valid triplets: [−2,6,4], [−2,6,3], [−2,4,3], [−2,4,8], [−2,3,8].

Algorithm

We use a three-pointer approach after sorting the array ?

  • Sort the array to enable efficient two-pointer technique

  • For each element at index i, use two pointers j and k

  • If sum is less than target, all elements between j and k form valid triplets

  • Move pointers based on the sum comparison

Implementation

def count_triplets(nums, target):
    nums.sort()
    count = 0
    n = len(nums)
    
    for i in range(n - 2):
        left = i + 1
        right = n - 1
        
        while left < right:
            current_sum = nums[i] + nums[left] + nums[right]
            
            if current_sum < target:
                # All triplets from left to right-1 are valid
                count += right - left
                left += 1
            else:
                right -= 1
    
    return count

# Test the function
nums = [-2, 6, 4, 3, 8]
target = 12
result = count_triplets(nums, target)
print(f"Number of triplets with sum < {target}: {result}")
Number of triplets with sum < 12: 5

How It Works

After sorting [-2, 3, 4, 6, 8], we iterate through each position as the first element ?

def count_triplets_detailed(nums, target):
    nums.sort()
    print(f"Sorted array: {nums}")
    count = 0
    n = len(nums)
    
    for i in range(n - 2):
        left = i + 1
        right = n - 1
        print(f"\nFirst element: nums[{i}] = {nums[i]}")
        
        while left < right:
            current_sum = nums[i] + nums[left] + nums[right]
            print(f"  Checking: {nums[i]} + {nums[left]} + {nums[right]} = {current_sum}")
            
            if current_sum < target:
                triplets_found = right - left
                count += triplets_found
                print(f"    Sum < {target}: Found {triplets_found} triplets")
                left += 1
            else:
                print(f"    Sum >= {target}: Moving right pointer")
                right -= 1
    
    return count

# Detailed example
nums = [-2, 6, 4, 3, 8]
target = 12
result = count_triplets_detailed(nums, target)
print(f"\nTotal triplets: {result}")
Sorted array: [-2, 3, 4, 6, 8]

First element: nums[0] = -2
  Checking: -2 + 3 + 8 = 9
    Sum < 12: Found 3 triplets
  Checking: -2 + 4 + 8 = 10
    Sum < 12: Found 2 triplets
  Checking: -2 + 6 + 8 = 12
    Sum >= 12: Moving right pointer

First element: nums[1] = 3
  Checking: 3 + 4 + 8 = 15
    Sum >= 12: Moving right pointer
  Checking: 3 + 4 + 6 = 13
    Sum >= 12: Moving right pointer

First element: nums[2] = 4
  Checking: 4 + 6 + 8 = 18
    Sum >= 12: Moving right pointer

Total triplets: 5

Time and Space Complexity

Aspect Complexity Reason
Time O(n²) Nested loops with two-pointer technique
Space O(1) Only using constant extra space

Conclusion

The two-pointer technique after sorting efficiently counts triplets with sum less than target. The key insight is that when sum < target, all combinations between the current left and right pointers are valid.

Updated on: 2026-03-25T11:40:43+05:30

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements