- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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

- Related Questions & Answers
- Program to find number of quadruples for which product of first and last pairs are same in Python
- Program to find length of longest contiguous sublist with same first letter words in Python
- Program to find number of operations needed to make pairs from first and last side are with same sum in Python
- Display records where first and last name begins with the same letter in MySQL
- Python program to interchange first and last elements in a list
- Program to pack same consecutive elements into sublist in Python
- 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
- Count numbers with same first and last digits in C++
- Count substrings with same first and last characters in C++
- Python Program to Swap the First and Last Value of a List
- Program to find all words which share same first letters in Python
- Program to find the size of the longest sublist where car speed is constant in python
- Maximum length of the sub-array whose first and last elements are same in C++

Advertisements