noodleProblems/
Geometric Sequence Triplets
#108

Geometric Sequence Triplets

AlgorithmmediumArrayHash Table

Given an array of integers nums and an integer r, count the **index triplets** (i, j, k) with i < j < k that form a geometric progression with common ratio r — that is, nums[j] === nums[i] * r **and** nums[k] === nums[j] * r.

Triplets are counted per index combination, so equal values at different positions produce distinct triplets. Return the total count.

Example cases

  • ratio 2 with repeats
    in nums = [2,1,2,4,8,8], r = 2
    out 5
    With middle value 4 (index 3): left has two 2s (indices 0, 2) and right has two 8s (indices 4, 5) → 2×2 = 4 triplets. With middle value 2 (index 2): left has one 1 (index 1) and right has one 4 (index 3) → 1 triplet. Total 5.
  • all equal, ratio 1
    in nums = [1,1,1,1], r = 1
    out 4
    When r = 1 every i < j < k of equal values qualifies: C(4, 3) = 4.
  • no valid triplet
    in nums = [1,2,4], r = 1
    out 0
    With r = 1 the three values would all have to be equal; they aren't.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • 1 <= r <= 10^9
Saved
nums =
[2,1,2,4,8,8]
r =
2