710262. Number of Triangles

Easy

Number of Triangles

Summary

Given a set of points in a two-dimensional space, find the number of triangles that can be formed using three points each. This problem requires an understanding of combinatorics and basic geometry.

Detailed Explanation

The key idea is to calculate the number of ways we can choose 3 points from the given set of n points. We can do this by choosing one point at a time, resulting in n options for the first point, n-1 options for the second point, and n-2 options for the third point. This gives us a total of n*(n-1)*(n-2) possible triangles.

However, we need to subtract 3 from this value because the three points chosen cannot form a triangle if they are collinear (i.e., lie on the same line). To account for this, we can calculate the number of ways to choose 3 collinear points using permutations and combinations. This gives us n*(n-1)/2 possible triangles.

The final step is to subtract this value from our initial calculation: n*(n-1)*(n-2) - n*(n-1)/2. This leaves us with the number of non-collinear triangles that can be formed using three points each, which is (n-2)*n*(n-1)/2.

Here's a step-by-step breakdown:

  1. Initialize num_triangles to 0.
  2. Calculate n*(n-1)*(n-2) as the total number of ways we can choose 3 points from the given set.
  3. Subtract n*(n-1)/2 to account for collinear triangles.
  4. The result is the number of non-collinear triangles that can be formed.

Time complexity: O(n^2) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public int numTriangles(int n) {
    return (n-2)*n*(n-1)/2;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.