Suppose we have a list of numbers called nums, we have to find the number of sublists where the first element and the last element are same.
So, if the input is like nums = [10, 15, 13, 10], then the output will be 5, as the sublists with same first and last element are: [10], [15], [13], [10], [10, 15, 13, 10].
To solve this, we will follow these steps −
num_sublists := size of nums
d := an empty map
for each n in nums, do
d[n] := d[n] + 1
for each number k and corresponding frequency v of elements in d, do
if v is not same as 1, then
num_sublists := num_sublists +(quotient of (v-1) *(v) /2)
return num_sublists
Let us see the following implementation to get better understanding −
Example
from collections import defaultdict class Solution: def solve(self, nums): num_sublists = len(nums) d = defaultdict(int) for n in nums: d[n] += 1 for k,v in d.items(): if v != 1: num_sublists += (v-1)*(v)//2 return num_sublists ob = Solution() nums = [10, 15, 13, 10] print(ob.solve(nums))
Input
[10, 15, 13, 10]
Output
5