Leetcode 259: 3Sum Smaller

https://leetcode.com/problems/3sum-smaller/

3Sum Smaller

Total Accepted: 1706 Total Submissions: 5006 Difficulty: Medium

Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.

For example, given nums = [-2, 0, 1, 3], and target = 2.

Return 2. Because there are two triplets which sums are less than 2:

[-2, 0, 1]
[-2, 0, 3]

Follow up:
Could you solve it in O(n2) runtime?

 

Code:

class Solution(object):
    def threeSumSmaller(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if nums is None or len(nums) <=2:
            return 0
        nums.sort()
        cnt = 0
        for k in xrange(2, len(nums)):
            i, j = 0, k-1
            while i < j:
                if nums[i] + nums[j] + nums[k] < target:
                    cnt += j - i
                    i += 1
                    j = k-1
                else:
                    j -= 1
        return cnt

 

Idea:

This is O(N^2) solution. You first sort nums in O(nlogn). Then, for every `k` in xrange(2, len(nums)), you start to pivot `i` at 0, and j on the left of `k`. Since nums is already a sorted array, if nums[i] + nums[j] + nums[k] < target, then fixing `i` and `k`, moving the index `j`  between`i+1` and `j` can always satisfy the inequality. On the other hand, if nums[i] + nums[j] + nums[k] >= target, you need to move j one position left and retry. The algorithm is O(N^2) because for each `k`, i and j will be traversed until they meet together in the middle of nums, i.e. `i` and `j` will be traversed together in O(N).

 

 

Leave a comment

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