Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

Count the triangles you can make

Medium · Target 15 minutes · Two pointers· Type asked at

You're given an array nums of non-negative integers and you have to return how many triples of indices i < j < k give you side lengths nums[i], nums[j] and nums[k] that can make a triangle. Three lengths make a triangle when each one's less than the other two added together.

Examples

InputOutputWhy
nums = [2, 2, 3, 4]3(2, 3, 4) twice, once for each 2, and (2, 2, 3). (2, 2, 4) fails because 2 + 2 is not more than 4.
nums = [4, 2, 3, 4]4
nums = [1, 2, 3]01 + 2 = 3, a flat triangle, which does not count.

Constraints

  • 0 ≤ n ≤ 1000
  • 0 ≤ nums[i] ≤ 1000

Hints

Hint 1

If you sort the three lengths so that a ≤ b ≤ c you'll only need to check one of the three inequalities. Which one is it?

Hint 2

It's a + b > c, because the other two hold already when c's the biggest. So you'd sort the whole array and fix c as the longest side.

Hint 3

With c fixed at index k you put lo = 0 and hi = k − 1. If nums[lo] + nums[hi] > c then every index from lo up to hi − 1 works with hi as well, so you can add hi − lo and move hi down. If it doesn't you move lo up.

Where people lose marks

  • Adding 1 on a hit and moving lo. You'll miss every other lo that works with the same hi and you're no longer counting pairs a range at a time.
  • Fixing the shortest side and scanning above it. Then a hit doesn't rule anything out in one direction and you can't count by ranges any more.
  • Counting a + b = c. That's a flat triangle with no area and the problem asks for a strict inequality.
  • Zeros. You'd think they need a special case but 0 + b > c can't hold when b ≤ c, so they drop out by themselves.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.