Program to find a sublist where first and last values are same in Python

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].

Algorithm

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

Example

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

How It Works

The algorithm works by counting occurrences of each element. For each element that appears multiple times, we calculate additional sublists that can be formed between any two positions of the same element using the formula (v-1) * v / 2, where v is the frequency.

Alternative Approach

We can also solve this using a direct approach without classes ?

def count_same_first_last_sublists(nums):
    count = len(nums)  # Single element sublists
    freq = {}
    
    # Count frequency of each element
    for num in nums:
        freq[num] = freq.get(num, 0) + 1
    
    # Add sublists with same first and last element
    for frequency in freq.values():
        if frequency > 1:
            count += (frequency - 1) * frequency // 2
    
    return count

nums = [10, 15, 13, 10]
result = count_same_first_last_sublists(nums)
print(f"Number of sublists with same first and last element: {result}")
Number of sublists with same first and last element: 5

Conclusion

The key insight is that single elements form valid sublists, and for elements appearing multiple times, we use the combination formula to count sublists between any two positions of the same element. This gives us an efficient O(n) solution.

Updated on: 2026-03-25T10:58:45+05:30

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements