How to Count Triplets: Methods, Patterns, and Efficient Algorithms

Counting triplets is a common problem in algorithms, data analysis, and coding interviews.

This guide explains how to count triplets efficiently, with patterns that work for ordered arrays, arithmetic relationships, and value-based constraints.

What Does It Mean to Count Triplets?

A triplet is any set of three elements chosen from a list, array, or sequence.

In many problems, the order of the three elements matters, while in others only the values or positions matter.

The first step in learning how to count triplets is identifying exactly which definition applies.

  • Index-based triplets: choose three positions such as i < j < k.
  • Value-based triplets: count combinations of numbers that satisfy a rule.
  • Ordered triplets: count permutations where sequence order changes the result.

Examples include counting triples with a specific sum, counting arithmetic progression triplets, and counting valid combinations under ratio or divisibility rules.

Use the Right Counting Model First

Before writing code, determine whether the problem is asking for combinations, permutations, or constrained index triples.

That choice affects the formula and the algorithm.

Combinations

If you only need to choose 3 items from n without regard to order, use the binomial coefficient:

C(n, 3) = n! / (3!(n - 3)!) = n(n - 1)(n - 2) / 6

This is the simplest case and appears when all triplets are equally valid.

Permutations

If the three chosen elements can appear in different orders and each order counts separately, use permutations instead.

For three distinct elements, that gives 3! = 6 arrangements per selection.

Index-constrained triplets

Many programming problems require i < j < k.

In these cases, the order of indices is fixed, and the challenge is usually to count the number of valid middle and end positions efficiently.

How to Count Triplets with Three Nested Loops

The most direct method is brute force: check every possible triplet.

This approach is easy to understand and useful for small inputs or for verifying a more advanced solution.

For an array of size n, the brute-force method checks all combinations of three indices, which costs O(n^3) time.

count = 0
for i in range(n):
    for j in range(i + 1, n):
        for k in range(j + 1, n):
            if condition(arr[i], arr[j], arr[k]):
                count += 1

This works, but it becomes too slow for large arrays.

Most efficient triplet-counting problems can be solved faster by using sorting, prefix sums, hash maps, or frequency tables.

How to Count Triplets Using Sorting and Two Pointers?

When the condition depends on sums or relative values, sorting often helps.

After sorting the array, you can fix one element and use two pointers to search for the remaining two.

This is especially useful for problems such as counting triplets whose sum is less than a target, equal to a target, or forms an arithmetic relationship.

For example, to count triplets with sum less than a value X:

  • Sort the array.
  • Fix the first index i.
  • Use left and right pointers for the other two positions.
  • If the sum is small enough, all pairs between left and right may be valid.

This reduces complexity to roughly O(n^2), which is a major improvement over brute force.

How to Count Triplets with Hash Maps?

Hash maps are helpful when the condition involves matching values or complements.

They let you track seen numbers and count how many ways a third value can complete a triplet.

A common pattern is counting triplets where the first two values determine the third.

For each pair or midpoint, you look up the needed complement in constant average time.

Typical use cases include:

  • Triplets that sum to a target.
  • Triplets formed by repeating values.
  • Triplets that satisfy a ratio, such as a, ar, ar^2 in a geometric progression.

For repeated values, a frequency map is often enough.

Suppose you need to count how many ways to choose three equal values.

If a number appears f times, the number of triplets is C(f, 3).

How to Count Triplets in a Sorted Array?

Sorted arrays make many counting tasks simpler because comparisons become easier and duplicate handling is more predictable.

When values are sorted, you can count blocks of equal numbers or use two pointers without repeatedly rechecking the same combinations.

For duplicate-heavy data, remember these rules:

  • Skip identical anchors only if the problem asks for unique triplets.
  • Count duplicates carefully if every index combination should be included.
  • Use multiplicity formulas when values repeat in a predictable way.

Example: if a sorted array contains multiple copies of the same number, and you are counting unique value triplets, you may need to collapse repeated runs into a single logical value before counting.

How to Count Triplets with a Specific Sum?

One of the most common interview questions is how to count triplets whose sum equals a target.

The fastest practical method usually combines sorting with a fixed first index and a two-pointer sweep for the other two values.

Steps:

  1. Sort the array.
  2. Fix index i from 0 to n - 3.
  3. Set left = i + 1 and right = n - 1.
  4. Move pointers based on whether the current sum is too small or too large.
  5. Count valid pairs when the sum matches the target.

This is a standard pattern for solving triplet-sum problems efficiently in O(n^2) time.

How to Count Arithmetic Triplets?

An arithmetic triplet is a set of values like x, x + d, and x + 2d.

These appear in sequence problems and numerical pattern recognition.

If the array is sorted, you can count arithmetic triplets by checking whether the next two expected values exist.

A hash set makes this very fast because membership tests are close to constant time.

seen = set(arr)
count = 0
for x in arr:
    if x + d in seen and x + 2*d in seen:
        count += 1

If duplicates matter, replace the set with a frequency map and count all valid index combinations rather than just distinct values.

How to Count Triplets in Geometric Progression?

In a geometric progression, a valid triplet may look like a, ar, ar^2.

This is a well-known counting problem because it can be solved in linear time with two maps.

The standard method tracks:

  • How many times each value has been seen so far.
  • How many partial pairs can be completed by the current value.

As you scan the array, update pair counts and final triplet counts based on the ratio.

This pattern is efficient and works well for large datasets.

Common Mistakes When Counting Triplets

  • Confusing combinations with permutations: the same three values may count once or six times depending on the rule.
  • Ignoring duplicates: repeated values can create many more valid triplets than expected.
  • Using brute force on large arrays: O(n^3) is often too slow.
  • Forgetting index order: some problems require i < j < k, not just any three positions.
  • Not sorting when needed: two-pointer methods usually depend on sorted input.

Choose the Best Approach for the Problem

If the input is small, brute force is fine.

If the problem asks for a target sum or relational pattern, sorting plus two pointers is often best.

If the rule depends on matching complements or repeated values, hash maps and frequency tables are usually the right tools.

In practice, learning how to count triplets means learning to recognize the structure of the condition first.

Once you identify whether the problem is about combinations, ordered indices, sums, or pattern matches, the counting method becomes much easier to choose.