Python coding

Triples that make a triangle

sides lists stick lengths (non-negative integers). Count the triples of different positions i < j < k whose three sticks can form a triangle with positive area, meaning each stick is shorter than the other two combined. Equal lengths at different positions make different triples.

Aim for O(n²) time instead of testing all O(n³) triples.

Besides the tests, one large input (400 sticks) with a ~250 ms limit (scaled to your device's speed): brute force won't pass.

  • count_triangles([3,4,5,6]) → 4
  • count_triangles([4,2,3,2]) → 3
  • count_triangles([1,2,3]) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Sort first. With a ≤ b ≤ c, the only check that matters is a + b > c, so fix the longest side c = a[k] and look for pairs in a[:k] with two pointers.

Hint 2

If a[lo] + a[hi] > a[k], every left end from lo to hi - 1 works with hi too, since none is shorter than a[lo]: count hi - lo at once. If not, a[lo] is too short.

Solution and why it works
pythonO(n²) · O(n) for the sorted copy
def count_triangles(sides: list[int]) -> int:
    a = sorted(sides)
    count = 0
    for k in range(2, len(a)):               # a[k] is the longest side
        lo, hi = 0, k - 1
        while lo < hi:
            if a[lo] + a[hi] > a[k]:
                count += hi - lo             # every left end in lo..hi-1 works with hi too
                hi -= 1
            else:
                lo += 1                      # a[lo] is too short even with a[hi]
    return count

After sorting, a triple is a triangle exactly when its two shorter sides sum to more than the longest, so fix the longest a[k] and run two pointers over a[:k]. If a[lo] + a[hi] > a[k], every left end from lo to hi - 1 is at least a[lo], so all of them work with a[hi]: count hi - lo at once and move hi. Otherwise move lo. O(n) per k, O(n²) total. Trap: > is strict; 1, 2, 3 lies flat.

Related lab: Loops in motion