3Sum Smaller
Updated
Problem statement
Given an array of n integers nums and an integer target, count the index triplets i, j, k with 0 <= i < j < k < n such that nums[i] + nums[j] + nums[k] < target.
Triplets are counted by index, so equal values at different positions form different triplets.
Function
threeSumSmaller(nums: int[], target: int) → intExamples
Example 1
nums = [-2,0,1,3]target = 2return = 2- The triplets with sum below 2 are
-2 + 0 + 1 = -1and-2 + 0 + 3 = 1. -2 + 1 + 3 = 2and0 + 1 + 3 = 4are not below 2, so the answer is 2.
Example 2
nums = []target = 0return = 0- There are no numbers, so there are no triplets.
Example 3
nums = [1,1,1,1]target = 4return = 4- Every triplet sums to 3, which is below 4. Four numbers give 4 triplets of indices, and each counts even though the values repeat.
Constraints
n == nums.length0 <= n <= 3500-100 <= nums[i] <= 100-100 <= target <= 100- The answer is at most
109.
More Salesforce Onsite Interview questions
- Count Increasing TripletsONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Reverse a Sublist of a Linked ListONSITE INTERVIEW · Seen Nov 2026
- Rotting OrangesONSITE INTERVIEW · Seen Nov 2026
- Count Zero Request ServersONSITE INTERVIEW · Seen Nov 2026
- Construct a Tree from Level-Order and Inorder TraversalsONSITE INTERVIEW · Seen Sep 2026
- Maximize Monsters DefeatedONSITE INTERVIEW · Seen Sep 2026
- Flatten Nested Map Paths with a StackONSITE INTERVIEW · Seen Sep 2026
- LFU CacheONSITE INTERVIEW · Seen Sep 2026
- Kth Largest Element in an ArrayONSITE INTERVIEW · Seen Sep 2026
Similar questions at other companies
- Count Winning Dice Face PairsGoogle · PHONE SCREENGoogle interview questions
- Count Centaur Friend RequestsMeta · PHONE SCREENMeta interview questions
- Count Triples That Can Form a TriangleAdobe · PHONE SCREENAdobe interview questions
- Search a Row- and Column-Sorted MatrixByteDance · ONSITE INTERVIEWByteDance interview questions
- Sort Ones, Twos, and Threes In PlaceAgoda · PHONE SCREEN · ONSITE INTERVIEWAgoda interview questions
- Minimum Station Tracks for a Train ScheduleBNSF Railway · ONSITE INTERVIEWBNSF Railway interview questions
- 4SumAmazon · ONSITE INTERVIEW
- Sort ColorsCapital One · ONSITE INTERVIEWCapital One interview questions
- 3SumOptimus Information · ONSITE INTERVIEWOptimus Information interview questions
- K Smallest Squares from a Sorted ArrayUber · ONSITE INTERVIEWUber interview questions