We are given: array of integers nums, and a ratio r. We need to count the number of triplets (i, j, k) with i<j<k such that nums[j]/nums[i] = r and nums[k]/nums[j] = r. So the condition is that the sequence nums[i], nums[j], nums[k] forms a geometric progression with ratio r. But note that we are dealing with integer division? The problem statement says "nums[j] / nums[i] == r". But careful: It might be floating point? Usually such problems require exact ratio, but since nums are integers and r is given (maybe integer? the problem says "for a given ratio r", but does not specify type. Typically in coding problems, r is integer? Could be float? But if r is a float, division of integers might not be exact. However, we can interpret as: nums[j] = nums[i] * r and nums[k] = nums[j] * r. So if r is integer, then we require nums[i]*r = nums[j] and nums[j]*r = nums[k]. But if r is not integer, we could have non-integer products? But nums are integers, so if r is not integer, then nums[j] might not be integer if we multiply by r? Actually we have nums[j] = nums[i] * r exactly, but if r is not integer, then nums[i]*r might not be integer, but nums[j] is integer. So for such exact equality to hold, r must be rational such that multiplication yields integer. But the condition is given as division equality, so we need to check if nums[j] / nums[i] equals r exactly (as a rational number). However, to avoid floating point inaccuracies, we can treat it as: nums[j] * denominator? But r is given as maybe a float? In typical coding problems, r is integer. I'll assume r is a number (could be integer or float?). The problem says "given ratio r". Possibly r is integer. But we can also think: we need to count triplets where j is the middle of a geometric progression with ratio r. We can use hash maps to count possibilities: iterate j from left to right? Actually we can do O(n^2) naive: for each j, count number of i<j such that nums[i] = nums[j]/r, and number of k>j such that nums[k] = nums[j]*r. Then total for j is left_count * right_count. Sum over j. That's O(n) per j if we can get counts in O(1) with hash maps. But careful: left_count depends on values, and right_count depends on values. We can precompute frequency maps? But need to consider ordering. Actually we need for each j: count i<j such that nums[i] = nums[j] / r. But note: r might be zero? Probably r is non-zero. If r=0, then condition becomes nums[j]/nums[i]=0 => nums[j]=0, and nums[k]/nums[j]=0 => nums[k]=0? But division by zero if nums[i]=0? So we need to handle edge cases. Usually r>0 and non-zero. We'll assume r is non-zero and also r is such that division yields integer? Actually we can treat as equality: nums[j] = nums[i] * r. That is better: we need to find i such that nums[i] * r = nums[j]. So if we have r as integer, then we can compute expected value for nums[i] as nums[j]/r. But if r is float, we cannot rely on integer arithmetic. But we can store frequencies of integers. So to avoid floating point issues, we can consider that nums are integers and r is rational? Actually if r is not integer, then nums[i] must be such that nums[i] * r is integer. That constrains possibilities. But we can treat as: For each j, we need to count i<j such that nums[i] = nums[j] / r. But we need to be careful about division: if r is not integer, then nums[j]/r might not be integer. So there would be no integer nums[i] that satisfies that unless nums[j] is divisible by denominator? But we can check: we want nums[i] exactly equal to some integer. So we can compute target = nums[j] / r. But if r is a float, then target might be non-integer. We can check if target is integer? Actually we can do rational arithmetic? But easier: we can use multiplication to avoid division: we want nums[i] * r = nums[j]. But if r is float, then left-hand side might be float, but we can still check equality? But we have integer nums[i] and integer nums[j]. So we could treat as: we need (nums[j] % r?) Not helpful.
Given typical programming contest problems, r is integer. So I'll assume r is integer. Also r can be negative? Possibly but then geometric progression with negative ratio? That is fine, but then ordering of indices still holds. So I'll assume r is integer and non-zero.
Thus approach: For each j, we want:
left_count = number of i<j such that nums[i] = nums[j] / r (and also that nums[j] is divisible by r? Actually if r integer, then we need nums[j] % r == 0 for there to be integer nums[i]. But if not divisible, then left_count=0.)
right_count = number of k>j such that nums[k] = nums[j] * r.
But careful: we need i<j<k. So we can't just count all future occurrences of nums[j]r because they may appear after j, but we also need them to be after j. Similarly for left, we need i<j. So we can process from left to right, maintaining a map (left_map) that counts frequency of each number seen so far. For each j, we compute left_target = nums[j] / r if divisible? Actually we need to check: if nums[j] % r != 0, then no integer left_target, left_count=0. But if we allow r to be rational? I'll stick to integer r and integer arithmetic. However, the problem statement didn't specify that r is integer; it said "given ratio r". It could be any number. But then using integer division would be wrong. To be safe, we might want to use multiplication: we want i such that nums[i] * r = nums[j]. That's equivalent: nums[i] = nums[j] / r. But if r is not integer, then we might have to store numbers as they are. In the map, we store integer values. For left, we need to find if there is any integer x such that x * r = nums[j]. That means x = nums[j] / r must be integer? But x is integer because it's from nums. So indeed we need that nums[j] is exactly divisible by r (if r integer) but if r is non-integer, we could have x such that x * r yields an integer nums[j] without requiring division to be integer. For example, r=2.5, nums[j]=5, then x=2 yields 22.5=5, integer. So x is integer but r is non-integer. So we can still treat x as integer: we need to check if there exists x in left_map such that x * r == nums[j]. But we cannot iterate over map. However we can compute x = nums[j] / r and see if x is integer? But x could be 2.0, it's integer? Actually we need x to be integer. So we need to check if nums[j] / r is an integer. But r could be non-integer; then the result might be non-integer. But we can check if it's an integer by verifying if nums[j] / r has no fractional part? In floating point it's messy. Alternatively, we can avoid division by using multiplication: we want to find x such that x = nums[j] / r. But we can also think: for each left number x, we need x * r = nums[j]. So if we store frequencies of numbers, then for current j we could compute left_count = left_map.get(nums[j] / r) but careful about integer division. We need to compute the exact rational value, but we are storing integers. So we need to see if the exact division yields an integer. That can be checked by: if r is integer, then require nums[j] % r == 0 and left_map.get(nums[j] // r). But if r is non-integer, then we need to check if nums[j] / r is integer. That can be done by checking if nums[j] * something? Actually if r is rational p/q (in reduced form), then condition becomes nums[i] * p / q = nums[j] => nums[i] * p = nums[j] * q. Since nums[i] integer, we require that nums[j] * q is divisible by p? Not necessarily. Better to avoid rational arithmetic.
Given typical problem statements, r is an integer. Many online problems: "Number of Geometric Triplets" with integer ratio. For example, LeetCode "Number of Triangular Triplets"? Not exactly. There is a known problem: "Count number of triplets that form a geometric progression" often with integer ratio. So I'll assume r is integer.
But even if r is not integer, we can still use a similar approach but with potential issues: we would need to store numbers and then for each j compute target = nums[j] / r, and see if target exists in left_map. But if r is not integer, target might be a non-integer; then we skip because left_map only contains integers. That's fine: we compute target = nums[j] / r as a float? Then check if target is an integer? Actually we need to check if target is integer and also present. But if r is 0.5, then nums[j]/0.5 = 2*nums[j] might be integer always. So we could compute target = nums[j] / r and then check if it is integer (i.e., if it is equal to a rounded integer). But that could cause floating point precision errors for large numbers. So if we want a robust solution for any rational r, we could represent r as a fraction (like a pair of integers) if given as such? The problem statement: "for a given ratio r". It doesn't say integer. Might be a float. But many coding challenge platforms expecting O(n) solution use integer r. I'll note that the O(n) solution using hash maps relies on integer arithmetic to compute exact targets. I think it's safe to assume r is integer, or at least that we can perform exact multiplication/division without overflow? We'll handle r as integer. Also we need to consider overflow? Use long? The problem says integers, could be large. Use Python's big ints.
But note: The condition is nums[j] / nums[i] == r and nums[k] / nums[j] == r. This is equivalent to nums[j] = nums[i] * r and nums[k] = nums[j] * r = nums[i] * r^2. So the triplet is (i,j,k) with values (a, ar, ar^2). So we can also think of counting pairs (i,k) with nums[i]r^2 = nums[k] and there exists j in between such that nums[j]=ar. But we need i<j<k.
The O(n) solution using hash maps: iterate through array, maintain two maps: left_count_map that counts occurrences of numbers to the left, and right_count_map that counts occurrences to the right? Actually we can do one pass? We can precompute a frequency map of all numbers (right_map initially). Then iterate j from left to right. At each step, we decrease right_map[nums[j]] (since j is no longer in the "right" part). Then compute left_target = nums[j] / r (if integer division possible) and right_target = nums[j] * r. Then left_count = left_map.get(left_target, 0), right_count = right_map.get(right_target, 0). Then add left_count * right_count to answer. Then increase left_map[nums[j]].
But careful: This assumes that for a given j, any i with nums[i]=left_target and any k with nums[k]=right_target will automatically satisfy i<j<k? We need i<j and j<k. Since we are iterating j in increasing order, left_map contains only indices less than j (since we add after processing j). Right_map contains indices greater than j (since we haven't processed them yet; we removed nums[j] from it before using). So indeed left_map counts all i<j with that value, right_map counts all k>j with that value. So this correctly counts triplets with j as the middle element.
But we must ensure that the left_target and right_target are integers? If r is integer, left_target = nums[j] // r only if divisible. But we should check divisibility: if nums[j] % r != 0, then left_target is not integer, but we could ignore because left_map only has integers, and even if we try to get left_map[nums[j]//r] that would be wrong because it's floor division. So we need to check: if r != 0 and nums[j] % r == 0, then left_target = nums[j] // r. If r==0? Then condition: nums[j]/nums[i] == 0 => nums[j]=0 (and nums[i]!=0? Actually division by zero if nums[i]=0; and if nums[i]=0, then 0/0 undefined. So r=0 is tricky. Probably r>0, non-zero. We'll assume r != 0. Also if r=0, then we would need nums[j]=0 and nums[k]=0 as well? Actually condition: nums[j]/nums[i]=0 => nums[j]=0 and nums[i] !=0? But if nums[i]=0, division undefined. So r=0 is not typical. We'll ignore or handle separately: if r==0, then we need nums[j]=0 and nums[i] any non-zero? Actually 0/x = 0 for any x !=0. So for i<j with nums[i]!=0, condition holds if nums[j]=0. And for j<k, nums[k]/0 undefined, so we cannot have nums[j]=0 because division by zero. So r=0 makes no sense unless we treat differently. Probably r>0.
Thus algorithm:
Initialize left_map = empty defaultdict(int)
Initialize right_map = count of all numbers (frequency map) using collections.Counter.
ans = 0
For each j from 0 to n-1:
# remove current from right_map because j is now the middle, so future k > j only
right_map[nums[j]] -= 1
if right_map[nums[j]] == 0: del right_map[nums[j]]
# compute left_target
if nums[j] % r == 0:
left_target = nums[j] // r
left_count = left_map.get(left_target, 0)
else:
left_count = 0
# compute right_target
right_target = nums[j] * r
right_count = right_map.get(right_target, 0)
# add product
ans += left_count * right_count
# add current to left_map for future i
left_map[nums[j]] += 1
Return ans.
This is O(n) time and O(n) space.
But is it correct? Consider the possibility of multiple i with same value, multiple k with same value. The product left_count * right_count indeed counts all combinations of i and k for a fixed j, since any i from left and any k from right will yield a valid triplet because nums[j] is exactly middle. So it's correct.
Edge cases: r negative? If r negative, then nums[j] % r? In Python, modulo with negative numbers may be tricky but still we can check divisibility: if nums[j] is not divisible by r exactly? For negative r, integer division and modulo work similarly: we need nums[j] / r = integer exactly. So we can check if nums[j] % r == 0. That works for negative r as well because Python's modulo yields remainder with same sign as divisor. For example, 10 % -3 = -2? Actually 10 % -3 gives -2? Let's check: 10 // -3 = -4, remainder = 10 - (-4)*(-3)=10-12=-2, so 10 % -3 = -2, not 0. But 12 % -3 = 0. So condition holds for exact division. So it's fine.
But we might also need to consider that nums are integers and r could be a rational number like 1/2? But then we cannot use integer division. But the problem might be from a source where r is integer. The specification: "given ratio r". It could be a float. But then we cannot use % operator. However we can treat condition as: nums[j] / nums[i] == r and nums[k] / nums[j] == r. This is equivalent to nums[i] * r = nums[j] and nums[j] * r = nums[k]. So if r is rational, we can store numbers as integers, but we need to multiply integers by r? Not integer. But we can also think: if we treat all as rational, maybe we can normalize? Another approach: we can use hash maps that store counts of numbers, but we need to compute left_target = nums[j] / r. That's division by r. If r is non-integer, left_target may be non-integer, but we need it to be integer to match an integer in the array. So we could check if division yields an integer: i.e., if nums[j] / r is integer, then we look it up. We could do this by checking if nums[j] % r == 0 only when r is integer. For non-integer, we can't use modulo. Could use fractions: if we represent r as a fraction (numerator, denominator) in reduced terms, then condition becomes: nums[j] = nums[i] * (p/q) => nums[i] = nums[j] * (q/p). And we need nums[i] integer. That implies that nums[j] * q must be divisible by p. Similarly for right: nums[k] = nums[j] * (p/q) => nums[k] = (nums[j] * p) / q and needs to be integer. So we could still do integer arithmetic if we handle fractions carefully. But the problem likely expects integer r. I'll note that in the explanation.
Thus the solution: O(n) time, O(n) space, using two hash maps.
Now we are asked: "You are given an array of integers nums. Write a function to find the number of 'geometric triplets'. ... Please write a function that solves this problem, and explain an efficient O(n) solution using hash maps."
So I need to produce code and explanation. I'll write a function countGeometricTriplets(nums, r) in Python.
Let's test with examples:
Example: nums = [1,2,4,8,16], r=2. The triplets: (0,1,2): 1,2,4; (0,1,3)? 1,2,8: 2/1=2, 8/2=4 no; Actually need ratio exactly r between consecutive: so (i,j,k) must be such that nums[j]=2nums[i] and nums[k]=2nums[j]=4*nums[i]. So for 1,2,4: works. Also (0,2,3): 1,4,8: 4/1=4 not 2. So only those where j is immediate? Not necessarily immediate in index but values must satisfy ratio. So check all: (0,1,2), (0,1,3)? 2/1=2 ok, 8/2=4 no. (0,1,4): 2/1=2, 16/2=8 no. (0,2,4): 4/1=4 no. (1,2,3): 2,4,8: 4/2=2, 8/4=2 yes. (1,2,4): 2,4,16: 4/2=2, 16/4=4 no. (1,3,4): 2,8,16: 8/2=4 no. (2,3,4): 4,8,16: 8/4=2, 16/8=2 yes. Also (0,3,?) none. So total 3 triplets. Our algorithm: iterate j.
Initialize left_map empty. right_map = Counter({1:1,2:1,4:1,8:1,16:1}).
j=0, nums[0]=1:
decrement right_map[1] -> 0, remove.
left_target: 1 % 2 !=0 -> left_count=0.
right_target = 1*2=2, right_count = right_map[2]=1.
ans += 0.
left_map[1]=1.
j=1, nums[1]=2:
decrement right_map[2] -> 0, remove.
left_target: 2%2==0 -> left_target=1, left_count=left_map[1]=1.
right_target=22=4, right_count=right_map[4]=1.
ans += 11 = 1.
left_map[2]=1.
j=2, nums[2]=4:
decrement right_map[4] -> 0, remove.
left_target: 4%2==0 -> left_target=2, left_count=left_map[2]=1.
right_target=42=8, right_count=right_map[8]=1.
ans += 11 = 1 -> ans=2.
left_map[4]=1.
j=3, nums[3]=8:
decrement right_map[8] -> 0, remove.
left_target: 8%2==0 -> left_target=4, left_count=left_map[4]=1.
right_target=82=16, right_count=right_map[16]=1.
ans += 11 =1 -> ans=3.
left_map[8]=1.
j=4, nums[4]=16:
decrement right_map[16] -> 0, remove.
left_target: 16%2==0 -> left_target=8, left_count=left_map[8]=1.
right_target=16*2=32, right_count=0.
ans unchanged.
left_map[16]=1.
Result=3. Good.
Another test: nums = [1,1,1], r=1. Triplets: any triple i<j<k: (0,1,2) only one? Actually all three 1's: for r=1, condition: nums[j]/nums[i]=1 and nums[k]/nums[j]=1 => all three equal. So number of triples? For n=3, only one triplet (0,1,2). But our algorithm: For each j, left_count = count of 1 in left, right_count = count of 1 in right. j=1: left has one 1, right has one 1 -> 1; j=2? Actually j=0: left none ->0; j=1: left_count=1 (from index0), right_count=1 (index2) ->1; j=2: left_count=2 (indices0,1), right_count=0 ->0. Sum=1. Good.
What about duplicates? nums = [1,2,2,4], r=2. Triplets? Let's list: i<j<k. Values: 1,2,4 -> we have index0:1; index1:2; index3:4 => (0,1,3). Also index0:1; index2:2; index3:4 => (0,2,3). Are there any with j=2 and i=1? i=1, j=2: nums[i]=2, nums[j]=2 -> 2/2=1 not 2. So no. So total 2. Algorithm: right_map init: {1:1,2:2,4:1}. Process j sequentially.
j=0: val=1, remove 1 from right (right_map[1]=0 remove). left_target 1%2 !=0 =>0. right_target=2, right_count=2. ans0. left_map[1]=1.
j=1: val=2, remove one 2 (right_map[2] becomes 1). left_target: 2%2==0 ->1, left_count=left_map[1]=1. right_target=4, right_count=1. ans+=1 =>1. left_map[2]=1.
j=2: val=2, remove one 2 (right_map[2]=0 remove). left_target: 2%2==0 ->1, left_count=left_map[1]=1. right_target=4, right_count=1. ans+=1 =>2. left_map[2]=2.
j=3: val=4, remove 4 (right_map[4]=0). left_target: 4%2==0 ->2, left_count=left_map[2]=2. right_target=8, right_count=0. ans unchanged.
Result=2. Good.
Edge: r=0? Not typical. We'll ignore or add condition if r==0: then triplet condition: nums[j]/nums[i]=0 => nums[j]=0 and nums[i]!=0? And nums[k]/nums[j]=0 => nums[k]=0 but division by zero if nums[j]=0. So invalid. So r cannot be zero. We'll assume r !=0.
What about negative r? Example: nums = [1,-2,4], r=-2. Check: 1 to -2: -2/1 = -2 ok. -2 to 4: 4/(-2) = -2 ok. So triplet exists. Algorithm: left_map and right_map handle negative numbers. left_target: nums[j] % r? For negative r, need to check divisibility: -2 % -2 = 0? Actually -2 % -2 = 0. 4 % -2? 4 % -2 = 0? Let's compute: 4 // -2 = -2? Actually 4 // -2 = -2, remainder 4 - (-2)*(-2)=4-4=0. So fine. So algorithm works.
But careful: integer division in Python: // does floor division. But if we have negative numbers and want exact division, we can check using multiplication: if nums[j] == (nums[j] // r) * r? That works only if exact? Actually if nums[j] is divisible by r, then nums[j] // r gives exact integer quotient (since floor division might differ for negative? In Python, when both numbers have same sign, // is truncation towards -inf? But if divisible exactly, then floor division gives exact quotient even for negatives. Example: -4 // 2 = -2, -4 % 2 = 0. 4 // -2 = -2, 4 % -2 = 0. So divisible exactly works fine. So using nums[j] % r == 0 is fine.
Thus solution is O(n) time, O(n) space.
We need to provide code and explanation. I'll write function:
def count_geometric_triplets(nums, r):
from collections import Counter, defaultdict
n = len(nums)
if n < 3:
return 0
left_map = defaultdict(int)
right_map = Counter(nums)
ans = 0
for j in range(n):
val = nums[j]
# remove val from right_map
right_map[val] -= 1
if right_map[val] == 0:
del right_map[val]
# left_count: number of i with nums[i] = val / r
if r != 0 and val % r == 0:
left_target = val // r
left_count = left_map.get(left_target, 0)
else:
left_count = 0
# right_count: number of k with nums[k] = val * r
right_target = val * r
right_count = right_map.get(right_target, 0)
ans += left_count * right_count
left_map[val] += 1
return ans
But note: what about overflow for multiplication? Python ints unlimited, fine.
But we need to consider case where r=0? We'll add guard: if r==0, then we need special handling: triplet condition: nums[j]/nums[i]=0 => nums[j]=0 and nums[i]!=0? Actually for any i, if nums[j]=0 and nums[i] !=0, then 0/nonzero =0. And for k: nums[k]/0 undefined unless nums[k]=0? But division by zero not allowed. So r=0 leads to no valid triplet because we cannot have nums[j]=0 as denominator for second ratio. Actually if r=0, then we require nums[k]/nums[j]=0 => nums[k]=0, but then denominator nums[j] must be non-zero? Actually if nums[j] non-zero, then nums[k]/nums[j]=0 => nums[k]=0. So possible: nums[i] any non-zero? But then first condition: nums[j]/nums[i]=0 => nums[j]=0. So we would need nums[j]=0 and nums[i] non-zero. That is possible. Then second condition: nums[k]/0? If nums[j]=0, then we are dividing by 0, undefined. So the second condition cannot be evaluated because division by zero. So r=0 yields no valid triplet because we can't have denominator zero. So we can return 0. So add if r == 0: return 0 early.
But some may interpret r=0 differently: they may define ratio by multiplication: nums[j] = nums[i] * r and nums[k] = nums[j] * r. Then if r=0, nums[j]=0 for any i (since multiply any by 0 gives 0). And then nums[k]=0 as well. But then condition would be satisfied if nums[i] arbitrary? Actually multiplication: nums[j] = nums[i] * 0 = 0, and nums[k] = nums[j] * 0 = 0. So that would give triplets: any i<j<k such that nums[j]=0 and nums[k]=0. But then i can be any (any value) because nums[i]0 always 0, but we require exactly that nums[j]==0. So condition becomes: nums[j]==0 and nums[k]==0. That would count triplets where middle and last are zero, with any i before j (with any value). That is a different interpretation. But original says "nums[j] / nums[i] == r". For r=0, that would be 0 = nums[j]/nums[i] => nums[j]=0 (provided nums[i] != 0). If nums[i]=0, then division undefined. So if we allow multiplication interpretation, we would have multiplication, not division, because division by zero issue. Usually geometric progression definition uses multiplication: each term is previous term times common ratio. That is ar and ar^2. So if r=0, second term is zero regardless of a, third term is zero regardless of second? Actually second term = a0 = 0, third term = (a*0)*0 = 0. So that yields triplets with second and third zero. But the first term a can be anything (including zero). But if a=0, then terms are 0,0,0. That is still valid? 0/0 undefined. So multiplication interpretation sidesteps division. The problem statement explicitly uses division: "nums[j] / nums[i] == r and nums[k] / nums[j] == r". So they are using division. So we must stick to division, which means denominators cannot be zero. So for r=0, we need nums[i] !=0 and nums[j]=0, and for second ratio, we need nums[j] !=0? Actually we need nums[k]/nums[j] == 0 => nums[k]=0, but denominator nums[j] must be non-zero? Because if nums[j]=0, division by zero is undefined. So for r=0, the second condition would require dividing by zero if nums[j]=0. So it's impossible unless we interpret ratio differently. So r=0 yields no valid triplet because second condition cannot be satisfied (unless we treat 0/0 as undefined). So we will return 0 for r=0.
Similarly, if r is not integer, we might still be able to use the same algorithm but with integer division? No, we need to compute left_target as val / r, which might be non-integer. But we only want integer target because nums are integers. So we can check if val / r is integer: that is, if val is exactly divisible by r in rational sense. If r is rational, we can represent as a fraction. But to keep it simple, I'll assume r is integer and note that in the explanation we can say "assuming r is integer". Alternatively, we can generalize: we can compute left_target = val / r, but since we only care if it's integer, we can check if val * denominator ... That seems messy. The problem likely expects integer r. I'll state assumption: r is integer, and nums are integers.
Actually the problem statement says "given ratio r" without specifying type. It might be a floating point number. But then the algorithm using multiplication might still work if we treat as floating? But then storing left_map with keys that are floating? But nums are integers, so left_target must be integer to match an integer in the array. So we can compute target = val / r as a rational. If it's integer, then we can convert to integer and check in map. So we need to check if division yields integer without floating errors. We can do: if r != 0 and (val * something) ??? Actually we can check if val % r == 0 only works for integer r. For float r, we could use something like: if abs(val / r - round(val / r)) < epsilon? But that's not safe for large integers. So we should assume integer r. The typical problem is "Given an array of integers and an integer r, count triplets ...". I'll go with that.
Now complexity: O(n) time, O(n) space.
But is there any catch? The approach counts each triplet exactly once, with j as middle. That's correct because each triplet has a unique j (the middle index). So sum over j gives total.
One more edge: r=1, then left_target = val, right_target = val. So we need to count ij with same value. This works as we saw.
What about r = -1? Then left_target = val // -1 = -val. That works if val % -1 ==0 (always true). So we count left occurrences of -val. That's fine.
But careful: For negative r, if val is positive, left_target negative; if val negative, left_target positive. That's fine.
Potential overflow in right_target multiplication: Python handles big ints.
Thus final code.
Now we need to provide explanation: Use two hash maps: left_counts (frequencies of numbers seen so far) and right_counts (frequencies of numbers remaining). Iterate j, update maps, compute left and right counts.
I'll write a detailed explanation.
Also note that we could also use a single pass with two maps initialized: left empty, right full. That's what we did.
We need to ensure that when we remove val from right_map before computing right_count, we don't count the current j as a future k. That's correct because we want k>j. And when we add to left_map after computing left_count, we don't count current j as i (since i<j). So correct.
Now I'll produce final answer.
But wait: What about the possibility that r is not integer, but we could still adapt: we could store numbers in left and right as is, and for each j, compute left_target = val / r as a float? Then check if that float is an integer? Not robust. Could use fractions.Fraction from Python: r = Fraction(r_num, r_den). But the input r might be given as float? We could ask the user to provide r as a rational? Not needed.
Given typical coding environment, r is integer. I'll proceed.
Also, the problem says "Write a function to find the number of 'geometric triplets'." So I'll implement the function.
Now let's consider potential bug: In Python, if r is negative and val is positive, val % r yields remainder with sign of divisor? Example: 5 % -2 = -1? Actually 5 // -2 = -3 because floor division: -3 * -2 = 6, remainder = -1. So 5 % -2 = -1, not 0. So 5 is not divisible by -2? But 5 divided by -2 is -2.5, not integer. So correct. For exact division, e.g., 6 % -2 = 0? 6 // -2 = -3, remainder 6 - (-3)*(-2)=6-6=0. So 6 is divisible by -2. So condition val % r == 0 correctly checks integer divisibility for negative r as well. Good.
But what about r = -1? 5 % -1 = 0? Actually any integer % -1 == 0 because any integer divided by -1 yields integer? Let's check: 5 // -1 = -5 (since floor? Actually -5 * -1 = 5, remainder 0). So 5 % -1 = 0. So all numbers divisible by -1. That's fine.
Thus code works.
Now I'll craft a response: Explanation and code.
I'll also include an example walkthrough.
Potential improvements: Use collections.defaultdict for left_map, but we can use dict and get.
Now I'll write final answer.
But note: The problem asks "explain an efficient O(n) solution using hash maps." So we need to explain in words the approach.
Thus my final answer will include:
- Problem restatement.
- Intuition: For each possible middle element j, the number of valid i is count of nums[i] = nums[j]/r to the left, and number of valid k is count of nums[k] = nums[j]*r to the right. Multiply for each j and sum.
- Implementation: maintain two frequency maps: left (numbers seen so far) and right (numbers not seen yet). Iterate through array, for each j: adjust right (decrement current), compute left_target and right_target, get counts, add product to result, then add current to left.
- Complexity O(n) time, O(n) space.
- Code.
I'll also mention handling of edge cases: r=0, non-integer r not considered. I'll state assumption that r is integer and non-zero.
But maybe the problem expects that we consider floating point r? Let's think: Could there be a known problem on LeetCode? There is "Number of Geometric Triplets" on LeetCode? Actually there is "Number of Boomerangs", "Number of Islands", etc. There is "Count Triplets That Can Form Two Arrays of Equal XOR" but not that. There is "Number of Triplets That Form a Geometric Progression"? I recall there is a problem: "Count the number of triplets in an array that form a geometric progression with a given common ratio". Yes, there is a HackerRank problem: "Count Triplets" where you have to count triplets (i,j,k) such that i<j<k and arr[j]/arr[i] = r and arr[k]/arr[j] = r. That problem expects O(n) solution using hash maps. And in that problem, r is given as an integer. The array elements are also integers. So it's exactly that. The constraints: 1 <= n <= 10^5, 1 <= arr[i] <= 10^9, 1 <= r <= 10^9. So r positive integer. So indeed it's from HackerRank. So I'll adopt that: r positive integer >0, and array contains positive integers. That also avoids negative/zero issues. The typical solution is exactly as described.
In that problem, they sometimes require handling large numbers, but Python fine.
Thus I'll proceed with positive integer r, and nums positive integers? Actually HackerRank's "Count Triplets" problem says: "You are given an array with distinct numbers? Actually I think it can have duplicates? Wait, the problem statement: "Given an array of integers and a ratio r, find the number of triplets (i,j,k) such that i<j<k and arr[j] = arr[i] * r and arr[k] = arr[j] * r." The array can have duplicates? I think yes. The sample input includes duplicates. For example, sample: [1, 3, 9, 9, 27, 81] r=3 yields 6? Let's recall: Actually HackerRank sample: array = [1, 2, 2, 4], r=2 -> answer 2. So duplicates allowed. So it's same.
In that problem, all numbers are positive? Possibly. But they didn't restrict to positive, but could be any positive. So no negative.
Thus our solution matches exactly.
Also note: In that problem, they sometimes require modulo 10^9+7? Not sure. But we can return integer.
So I'll write solution accordingly.
Potential nuance: If r == 1, we must be careful: left_target = val, right_target = val. Our algorithm works.
Now I'll produce final answer.
Let's include some test cases in code? Not necessary but we can.
I'll also discuss why O(n): single pass, hash map operations O(1) average.
Now write final.
Solution Explanation
We need to count all index triples (i, j, k) with i < j < k such that
nums[j] / nums[i] = r and nums[k] / nums[j] = r
which is equivalent to
nums[j] = nums[i] * r and nums[k] = nums[j] * r .
For a fixed middle position j the conditions become:
- choose an index
i left of j with nums[i] = nums[j] / r
- choose an index
k right of j with nums[k] = nums[j] * r
If there are L possible i's and R possible k's, then L * R triples have j as their middle element.
Summing this product over all j gives the total answer.
The challenge is to obtain L and R for every j in O(1) time.
We achieve this with two hash maps that store frequencies:
left_map – counts of numbers already processed (i < j).
right_map – counts of numbers not processed yet (k > j). Initially it contains the whole array.
We iterate j from left to right:
- Remove
nums[j] from right_map because j itself is no longer a future k.
- Compute the left target:
target_left = nums[j] / r.
Because all numbers are integers and r is an integer, target_left must be an integer; we only consider it when nums[j] is exactly divisible by r. Otherwise L = 0.
- Compute the right target:
target_right = nums[j] * r.
L = left_map.get(target_left, 0)
R = right_map.get(target_right, 0)
- Add
L * R to the answer.
- Insert
nums[j] into left_map for the next positions.
All map operations are O(1) average, so the whole algorithm runs in O(n) time and uses O(n) extra space.
Edge cases
r = 0 – division by zero occurs in the definition, thus no valid triplets. We return 0.
r negative – the same logic works; the divisibility check nums[j] % r == 0 is still valid in Python.
- Large numbers – Python integers have arbitrary precision, so overflow is not an issue.
Correctness Proof
We prove that the algorithm returns exactly the number of geometric triplets.
Lemma 1
At any iteration j, left_map contains every nums[i] with i < j and no other numbers.
Proof.
left_map starts empty. After processing an index p we insert nums[p]. Hence before processing j, all indices < j have been inserted, and no index ≥ j has been inserted because we insert only after the computation for that index. ∎
Lemma 2
At any iteration j, right_map contains every nums[k] with k > j and no other numbers.
Proof.
Initially right_map holds all array elements. At the beginning of iteration j we remove nums[j]. After that removal, all indices > j remain (they have not been removed yet), and index j itself is gone. No element with index < j will ever appear again because we only delete, never re‑add. ∎
Lemma 3
For a fixed j, the value L = left_map.get(target_left, 0) equals the number of indices i < j satisfying nums[i] = target_left, i.e. nums[j] / nums[i] = r.
Proof.
By Lemma 1, left_map exactly records the multiset of values at positions < j.
If nums[j] is not divisible by r, no integer target_left can satisfy nums[i] * r = nums[j]; the algorithm safely sets L = 0.
If divisible, target_left = nums[j] // r is the unique integer that fulfils target_left * r = nums[j].
left_map.get returns the count of that integer among indices < j. ∎
Lemma 4
For a fixed j, the value R = right_map.get(target_right, 0) equals the number of indices k > j satisfying nums[k] = target_right, i.e. nums[k] / nums[j] = r.
Proof.
By Lemma 2, right_map exactly records the multiset of values at positions > j.
target_right = nums[j] * r is the unique integer (since r is integer) that fulfils nums[j] * r = target_right.
The map lookup returns how many times that value occurs to the right of j. ∎
Lemma 5
For a fixed j, the product L * R equals the number of triples (i, j, k) with i < j < k that satisfy both ratio conditions and have middle index j.
Proof.
Every pair (i, k) with i from the L left candidates and k from the R right candidates automatically satisfies:
nums[j] = nums[i] * r (by definition of target_left)
nums[k] = nums[j] * r (by definition of target_right)
Hence the triple (i,j,k) is valid.
Conversely, any valid triple with middle j must use an i with nums[i] = target_left and a k with nums[k] = target_right. Those are counted exactly by the sets of size L and R. Since the choice of i and k are independent, there are L·R such triples. ∎
Theorem
The algorithm returns the total number of geometric triplets in nums.
Proof.
The answer is accumulated as ans += L_j * R_j for each j.
By Lemma 5, L_j * R_j counts exactly the triples with middle index j.
Different j values produce disjoint sets of triples because a triple has a unique middle element.
Therefore the sum over all j equals the total number of valid triples. ∎
Complexity Analysis
Time: One pass over n elements. Each step does a constant number of hash‑map operations → O(n).
Space: Two hash maps store at most n distinct values → O(n).
Reference Implementation (Python 3)
from collections import defaultdict, Counter
def count_geometric_triplets(nums, r):
"""
Count the number of triplets (i, j, k) with i < j < k such that
nums[j] / nums[i] == r and nums[k] / nums[j] == r.
Assumes r is a non‑zero integer. If r == 0, returns 0 because the
second ratio would involve division by zero.
"""
if r == 0:
return 0 # division by zero would occur, no valid triplets
n = len(nums)
if n < 3:
return 0
left_map = defaultdict(int) # counts of numbers seen so far (i < j)
right_map = Counter(nums) # counts of numbers not processed yet (k > j)
ans = 0
for j in range(n):
val = nums[j]
# current element is no longer a future k
right_map[val] -= 1
if right_map[val] == 0:
del right_map[val]
# count of i with nums[i] = val / r
left_count = 0
if val % r == 0: # exact division check for integer r
left_target = val // r
left_count = left_map.get(left_target, 0)
# count of k with nums[k] = val * r
right_target = val * r
right_count = right_map.get(right_target, 0)
ans += left_count * right_count
# make val available for future i
left_map[val] += 1
return ans
Example
>>> count_geometric_triplets([1, 2, 2, 4], 2)
2
>>> count_geometric_triplets([1, 2, 4, 8, 16], 2)
3
>>> count_geometric_triplets([1, 1, 1], 1)
1
The function runs in linear time and uses linear additional memory, satisfying the efficiency requirement.