File: number-of-unequal-triplets-in-array/solution.py

Date: 2026-06-06

Time: 18:24

number-of-unequal-triplets-in-array/solution.py

Purpose

Solves LeetCode 2475: given an array nums, count index triplets (i, j, k) with i < j < k where all three values are pairwise distinct (nums[i] != nums[j], nums[j] != nums[k], nums[i] != nums[k]).

Key Components

Solution.countTriplets(nums: List[int]) -> int — The single method. Takes a list of positive integers, returns the count of valid triplets.

Patterns

The solution uses a group-contribution sweep rather than brute-force enumeration. Instead of O(n³) nested loops, it:

1. Groups elements by value via Counter(nums).

2. Sweeps through the groups in arbitrary order, maintaining a running left count of elements in already-processed groups.

For each group with count c:

This works because any set of three elements with pairwise distinct values spans exactly three distinct groups. That triple of groups is counted exactly once — when the group that falls in the middle of the processing order is visited. The index ordering constraint (i < j < k) is satisfied because choosing 3 items from 3 groups yields 1 ordered arrangement each, and a * b * c already counts all unordered selections which map 1-to-1 to ordered index triples.

Dependencies

Imports:

Imported by: The corresponding test_solution.py in the same directory.

Flow


nums = [4, 4, 2, 4, 3]

Counter(nums) → {4: 3, 2: 1, 3: 1}

Iteration:
  c=3 (value 4): left=0, right=5-0-3=2  → 0*3*2 = 0
  c=1 (value 2): left=3, right=5-3-1=1  → 3*1*1 = 3
  c=1 (value 3): left=4, right=5-4-1=0  → 4*1*0 = 0

result = 3

Invariants

Complexity

Error Handling

None. The method trusts its input matches LeetCode constraints (1 <= nums.length <= 1000, 1 <= nums[i] <= 1000). No edge-case guards for empty arrays — unnecessary given the constraint.

Beliefs