Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 the 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, where k = 2. If we select the sublist [30, 40, 30], this is the shortest sublist where 30 appears with its maximum frequency of 2.
Algorithm
To solve this, we will follow these steps −
- L := size of nums
- rnums := reverse of nums
- d := a map containing frequencies of each element present in nums
- mx := maximum frequency from all values in d
- vs := a list of elements k where d[k] equals mx
- mn := L (initialize minimum length)
- For each element v in vs, calculate the shortest sublist length containing all occurrences of v
- 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]
# Count frequency of each element
d = Counter(nums)
mx = max(d.values())
# Find all elements with maximum frequency
vs = [k for k in d if d[k] == mx]
mn = L
for v in vs:
# Calculate shortest sublist for element v
first_index = nums.index(v)
last_index = L - rnums.index(v) - 1
sublist_length = last_index - first_index + 1
mn = min(mn, sublist_length)
return mn
# Test the function
nums = [10, 20, 30, 40, 30, 10]
result = solve(nums)
print(f"Input: {nums}")
print(f"Shortest sublist length: {result}")
Input: [10, 20, 30, 40, 30, 10] Shortest sublist length: 3
How It Works
The algorithm works by finding the first and last occurrence of each most frequent element. For element 30 in our example:
- First occurrence at index 2
- Last occurrence at index 4
- Shortest sublist containing both:
[30, 40, 30]with length 3
Similarly for element 10, the sublist would be [10, 20, 30, 40, 30, 10] with length 6. The minimum is 3.
Conclusion
This solution efficiently finds the shortest sublist by identifying elements with maximum frequency and calculating the span between their first and last occurrences. The time complexity is O(n) where n is the length of the input list.
---