Valid Triangle Number

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

You are given an array nums of non-negative integers representing stick lengths. Count the number of index triples i < j < k whose three lengths can form a triangle with positive area, meaning the sum of any two of the lengths is strictly greater than the third. Triples are counted by index, so equal lengths at different positions produce distinct triples. Aim for O(n^2) time.

Examples

Input: nums = [3,3,4,5]
Output: 4
All four index triples work: (3,3,4), (3,3,5), and (3,4,5) twice (once with each 3).
Input: nums = [1,2,3,0]
Output: 0
1 + 2 is not strictly greater than 3, and any triple with 0 is degenerate.

Constraints

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000

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