Problem Description
Given an array of integers and a target value, count the number of triplets (i, j, k) with 0 <= i < j < k < n such that the sum of the three numbers is less than the target.
Key Insights
- Sort the array to leverage the inherent order.
- Use a two pointers approach for each fixed element to efficiently count valid pairs.
- When a valid pair is found, all elements between the left and right pointers yield valid triplets.
- Avoid redundant calculations by adjusting pointers based on the sum comparison with the target.
Space and Time Complexity
Time Complexity: O(n^2)
Space Complexity: O(1) (or O(log n) if considering the sorting stack space)
Solution
Sort the array first. Then, iterate through the array using an index i, and for each i, use two pointers (left and right) to check pairs (j, k) such that the sum of nums[i] + nums[left] + nums[right] is less than the target. When the condition is met, all elements between left and right will also form valid triplets with the current i, so add (right - left) to the count and move the left pointer. If the sum is equal to or exceeds the target, move the right pointer leftwards to reduce the sum. This approach leverages the sorted order to count multiple valid pairs at once, resulting in an O(n^2) time complexity.