
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find length of shortest sublist with maximum frequent element with same frequency in Python
Suppose we have a list of numbers called nums. If the frequency of a most frequent number in nums is k. We have to find the length of a shortest sublist such that the frequency of its most frequent item is also k.
So, if the input is like nums = [10, 20, 30, 40, 30, 10], then the output will be 3, because here the most frequent numbers are 10 and 30 , here k = 2. If we select the sublist [30, 40, 30] this is the shortest sublist where 30 is present and its frequency is also 2.
To solve this, we will follow these steps −
- L := size of nums
- rnums := reverse of nums
- d := a map containing frequencies of each elements present in nums
- mx := maximum of list of all values of d
- vs := a list of k for each k in d if d[k] is same as mx
- mn := L
- for each v in vs, do
- mn := minimum of mn and ((L - (index of v in rnums) - (index of v in nums))
- return mn
Example
Let us see the following implementation to get better understanding −
from collections import Counter def solve(nums): L = len(nums) rnums = nums[::-1] d = Counter(nums) mx = max(d.values()) vs = [k for k in d if d[k] == mx] mn = L for v in vs: mn = min(mn, (L - rnums.index(v)) - nums.index(v)) return mn nums = [10, 20, 30, 40, 30, 10] print(solve(nums))
Input
[10, 20, 30, 40, 30, 10]
Output
3
- Related Articles
- Program to find length of longest contiguous sublist with same first letter words in Python
- Program to find frequency of the most frequent element in Python
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find length of longest sublist with given condition in Python
- Program to find length of longest consecutive sublist with unique elements in Python
- Program to find length of longest sublist with value range condition in Python
- Program to find maximum length of k ribbons of same length in Python
- Program to find length of shortest supersequence in Python
- Program to find maximum length of subarray with positive product in Python
- Program to find length of longest distinct sublist in Python
- Program to find the maximum sum of circular sublist in Python
- Program to find length of contiguous strictly increasing sublist in Python
- Program to find maximum XOR with an element from array in Python
- Find the sublist with maximum value in given nested list in Python
- Program to find length of longest alternating inequality elements sublist in Python

Advertisements