3Sum Smaller

MediumTwo Pointerstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums and an integer target, count the index triplets (i, j, k) with 0 <= i < j < k < nums.length such that nums[i] + nums[j] + nums[k] < target. Triplets are counted by position, so equal values at different indices form different triplets. Return the count. An O(n^2) solution is expected.

Examples

Input: nums = [-2,0,1,3], target = 2
Output: 2
Only `[-2, 0, 1]` (sum -1) and `[-2, 0, 3]` (sum 1) are below 2.
Input: nums = [], target = 0
Output: 0
There are no triplets.
Input: nums = [0], target = 0
Output: 0
One element cannot form a triplet.

Constraints

  • 0 <= nums.length <= 3500
  • -100 <= nums[i] <= 100
  • -100 <= target <= 100

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems