{x}
blog image

3Sum Smaller

Solution Explanation: 3Sum Smaller

This problem asks to find the number of triplets in an array whose sum is less than a given target. The optimal approach leverages sorting and a two-pointer technique for efficient counting.

Approach:

  1. Sorting: First, we sort the input array nums. Sorting allows us to efficiently use the two-pointer method because it enables us to quickly identify potential triplets whose sums are less than the target. The time complexity of sorting is O(n log n), where n is the length of the array.

  2. Two Pointers and Enumeration: We iterate through the sorted array using a single loop (outer loop). For each element nums[i] (the first element of a potential triplet), we employ two pointers, j and k, initially pointing to i + 1 and the end of the array, respectively.

  3. Sum and Comparison: We calculate the sum x of the triplet nums[i] + nums[j] + nums[k].

  4. Conditional Actions:

    • If x < target, it means we've found a triplet satisfying the condition. Since the array is sorted, any element k' such that j < k' <= k will also satisfy nums[i] + nums[j] + nums[k'] < target. Thus, we add k - j (the number of such elements) to our ans (the count of triplets). We then increment j to consider the next potential triplet with nums[i].

    • If x >= target, it implies that any triplet including nums[k] (or a larger element) will have a sum greater than or equal to the target. Therefore, we decrement k to try another potential triplet with a smaller sum.

  5. Iteration: We continue this process until j and k cross each other (meaning all possible triplets with nums[i] as the first element have been checked). The outer loop then proceeds to the next i to repeat the process for all possible first elements of triplets.

  6. Return Value: Finally, we return ans, which holds the total count of triplets whose sums are less than the target.

Time Complexity Analysis:

  • Sorting: O(n log n)
  • Nested loops (outer loop iterates n times; inner loop (two pointers) iterates at most n times for each outer loop iteration): O(n^2)
  • Overall, the time complexity is dominated by the nested loops, resulting in O(n^2).

Space Complexity Analysis:

  • The space complexity is O(log n) due to the space used by the sorting algorithm (for example, merge sort or quicksort, which use recursion). In-place sorting algorithms would have a space complexity of O(1). We are not using any extra space proportional to the input size.

Code Examples (Python):

def threeSumSmaller(nums, target):
    nums.sort()
    ans = 0
    n = len(nums)
    for i in range(n - 2):
        j = i + 1
        k = n - 1
        while j < k:
            x = nums[i] + nums[j] + nums[k]
            if x < target:
                ans += k - j
                j += 1  # Move j to explore larger sums
            else:
                k -= 1  # Move k to explore smaller sums
    return ans

The code in other languages (Java, C++, Go, TypeScript, JavaScript) follows the same algorithm and logic, only differing in syntax and specific library functions used for sorting and array manipulation. The core algorithm and its time/space complexity remain the same.