How to count triplets of i,j,k such that i < j < k

Question:

I want to know an efficient way of calculating the count of triplets i, j, and k such that i < j < k.

I’ve tried using the following code:

for i in range(n):
  for j in range(i + 1, n):
    for k in range(j + 1, n):
      ans += 1

But that would result in O(N3) time complexity and that is not very efficient. O(N log N) time complexity (or faster) would be optimal.

Asked By: Dilophosaurus8

||

Answers:

You don’t need any loops. There is a closed form formula for this:

1/6 n(n**2 - 3n + 2)

Or:

1/6 (n - 2)(n - 1)n

Answered By: John Kugelman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.