We need to solve: "You are given an array of integers nums. Write a function to find the number of subarrays where the first and last elements are the same." We need to provide a function that solves this problem and explain the algorithm. We should consider efficiency. The naive solution: O(n^2) iterate over all subarrays and check if first and last equal. But we can do better.
Observation: For any value v, we want to count subarrays that start and end with v. For each occurrence of v at positions p1, p2, ..., pk (in increasing order). A subarray with first and last both v can be defined by choosing start position i and end position j such that i <= j, and nums[i] = nums[j] = v. But also note that subarray includes elements between them; we don't care about interior values. So for a given v, the number of subarrays with first and last equal to v is the number of pairs (i, j) with i <= j from the positions where nums equals v. That is: if we have k occurrences, then number of pairs (i,j) with i <= j is C(k,2) + k = k*(k+1)/2. Because each occurrence alone (i=j) counts as a subarray of length 1 where first and last same trivially (single element). So total = sum over v of (count_v * (count_v + 1) / 2). But is that correct? Let's double-check: For a subarray defined by start index i and end index j (inclusive), we require nums[i] = nums[j]. The interior doesn't matter. So indeed any pair (i, j) with i <= j and same value qualifies. So we just need to count pairs of equal values (including self-pairs). That's exactly sum_{v} count_v choose 2 + count_v = count_v*(count_v+1)/2.
But wait: Is there any subtlety about overlapping subarrays? No, we are just counting all possible subarrays. So this is O(n) time to count frequencies and then compute sum. However, note: The number of distinct values may be large, but we can use a hashmap (dictionary) to count frequencies.
Thus the algorithm:
- Initialize a dictionary freq.
- For each num in nums, increment freq[num].
- For each count in freq.values(), add count*(count+1)//2 to result.
- Return result.
Edge cases: empty array? If nums is empty, there are no subarrays; result 0. The sum will be 0 as no frequencies.
Check example: nums = [1,2,1,2]? Let's compute: occurrences: 1 appears twice => 23/2=3; 2 appears twice => 3; total 6. Let's enumerate subarrays: all subarrays: [1], [2], [1], [2], [1,2], [2,1], [1,2], [1,2,1], [2,1,2], [1,2,1,2]? Actually there are n(n+1)/2 = 10 subarrays. Which ones have first=last? Singletons: 4. Then length 2: [1,2] not; [2,1] not; [1,2] not. length 3: [1,2,1] first=last=1 yes; [2,1,2] first=last=2 yes. length 4: [1,2,1,2] first=1, last=2 no. So total 6. matches.
Another: nums = [1,1,1] => count=3 => 3*4/2=6. Subarrays: [1] (3), [1,1] (2), [1,1,1] (1) => total 6.
Thus formula is correct.
Now, implementation in Python: def count_subarrays(nums): ...
Complexity: O(n) time, O(n) space (for frequency map). Could be O(1) space if values are bounded? But we use map.
We need to write a function and explain algorithm.
But the user said: "You are given an array of integers nums. Write a function to find the number of subarrays where the first and last elements are the same. Please write a function that solves this problem, and explain your algorithm." So we should provide solution. Possibly they expect to handle large arrays, so O(n) solution is appropriate.
Thus we'll write code in Python with explanation.
We can also mention that we are counting all pairs (i, j) with i <= j and nums[i] == nums[j].
Edge cases: negative numbers? Works fine.
Now produce answer: We'll write a function count_subarrays(nums). Provide explanation.
We can also note that if we wanted only subarrays of length >=2? The problem says "subarrays where the first and last elements are the same." That includes length 1 because first and last are the same element. Usually single element subarray qualifies because first and last are same element. But sometimes problems ask for subarrays of length at least 2? But typical interpretation includes length 1. However, we should check: "first and last elements are the same" For a single element, first = last = that element, so it qualifies. So our count includes those. If they wanted length>1, they'd specify. So we include length 1.
But we can discuss: If the problem intended subarrays with at least two elements, then we would subtract n from total. But they didn't specify. Usually these problems count subarrays of any length. We'll assume any length.
We'll write the function accordingly. But maybe we should ask? Since it's an explanation, we can state: "If subarrays of length 1 are counted, then total = sum_v C(cnt_v+1, 2) = sum_v cnt_v*(cnt_v+1)/2. If only length>=2, then subtract total number of elements." But we'll go with any length.
We'll provide both possibilities in explanation.
Now produce final answer.
Solution Explanation
For a subarray we only care about its first and last elements.
A subarray nums[i … j] (with i ≤ j) satisfies the condition if
nums[i] == nums[j]
The values in the middle do not matter.
So the problem reduces to counting all index pairs (i, j) with i ≤ j such that the elements at those positions are equal.
Key Insight
Group the array indices by the value that appears there.
Suppose a particular value v occurs at k different positions.
From those k positions we can pick any ordered pair (i, j) with i ≤ j to form a valid subarray:
- Choosing the same index for start and end (
i = j) gives a subarray of length 1.
- Choosing two different indices (
i < j) gives a subarray of length ≥ 2.
The number of ordered pairs (i, j) with i ≤ j from k items is:
# of pairs = C(k, 2) + k = k*(k-1)/2 + k = k*(k+1)/2
where the first term counts distinct indices (length ≥ 2) and the second term counts the k self‑pairs (length 1).
Therefore, if we know the frequency cnt[v] of every distinct value v in the array, the total number of required subarrays is
total = Σ_{v} cnt[v] * (cnt[v] + 1) / 2
Algorithm
- Count frequencies of each integer in
nums using a hash map (dict in Python).
- Sum contributions: for each frequency
c, add c * (c + 1) // 2 to the answer.
- Return the accumulated sum.
Correctness Proof
We prove that the algorithm returns exactly the number of subarrays whose first and last elements are equal.
Lemma 1
For any fixed value v that appears k times in nums, the number of subarrays whose first and last elements are both v equals k*(k+1)/2.
Proof.
Let the positions where nums[pos] == v be p1 < p2 < … < pk.
A subarray with first and last v is uniquely determined by choosing a start index pi and an end index pj with i ≤ j.
There are k choices for i and, for each i, k - i + 1 choices for j (all positions from pi onward).
Summing gives Σ_{i=1}^{k} (k - i + 1) = k + (k-1) + … + 1 = k*(k+1)/2.
Equivalently, this is the number of ordered pairs (i, j) with i ≤ j from a set of size k. ∎
Lemma 2
Subarrays counted for different values v1 ≠ v2 are disjoint (no subarray belongs to two different values).
Proof.
If a subarray has its first element equal to v1 and also equal to v2, then v1 = v2. Hence a subarray can only be associated with a single value. ∎
Theorem
The algorithm returns the exact number of subarrays where the first and last elements are the same.
Proof.
Let cnt[v] be the frequency of value v. By Lemma 1, value v contributes exactly cnt[v]*(cnt[v]+1)/2 valid subarrays.
By Lemma 2, contributions from distinct values are non‑overlapping, so the total number of valid subarrays is the sum over all v of these contributions.
The algorithm computes precisely this sum, thus its output equals the desired count. ∎
Complexity Analysis
Time:
- Counting frequencies:
O(n) where n = len(nums).
- Summing over the hash map:
O(m) where m is the number of distinct values (m ≤ n).
Overall O(n).
Space:
The hash map stores at most m entries, i.e., O(m) ≤ O(n) extra space.
Reference Implementation (Python 3)
def count_subarrays(nums):
"""
Returns the number of subarrays where the first and last elements are the same.
Parameters:
nums (List[int]): input array of integers.
Returns:
int: count of such subarrays.
"""
from collections import defaultdict
# Step 1: count frequencies of each value
freq = defaultdict(int)
for num in nums:
freq[num] += 1
# Step 2: sum contributions
total = 0
for c in freq.values():
total += c * (c + 1) // 2 # integer arithmetic
return total
# Example usage:
if __name__ == "__main__":
print(count_subarrays([1, 2, 1, 2])) # Output: 6
print(count_subarrays([1, 1, 1])) # Output: 6
print(count_subarrays([])) # Output: 0
The function follows exactly the algorithm proven correct above and runs in linear time.