- Related Questions & Answers
- Display records where first and last name begins with the same letter in MySQL
- Program to pack same consecutive elements into sublist in Python
- Python program to interchange first and last elements in a list
- Program to find size of sublist where product of minimum of A and size of A is maximized in Python
- Python Program to Form a New String where the First Character and the Last Character have been Exchanged
- Program to find length of longest sublist where difference between min and max smaller than k in Python
- Python Program to Swap the First and Last Value of a List
- Program to find the size of the longest sublist where car speed is constant in python
- Count numbers with same first and last digits in C++
- Count substrings with same first and last characters in C++
- Program to find all words which share same first letters in Python
- Maximum length of the sub-array whose first and last elements are same in C++
- Get last element of each sublist in Python
- Program to find length of longest distinct sublist in Python
- Find First and Last Position of Element in Sorted Array in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

[10, 15, 13, 10]

5

Advertisements