Program to check every sublist in a list containing at least one unique element in Python


Suppose we have a list of elements called nums, we have to check whether every sublist has at least 1 element in it that occurs exactly once in the sublist or not. We have to solve this problem in linear time.

So, if the input is like nums = [5, 10, 20, 10, 0], then the output will be True, because every sublist in nums has at least one element which has occurred only once. [[5], [10], [20], [10], [0], [5,10], [10,20], [20,10], [10,0], [5,10,20], [10,20,10], [20,10,0], [5,10,20,10], [10,20,10,0], [5,10,20,10,0]] all have at least one element whose frequency is 1.

To solve this, we will follow these steps −

  • Define a function has_unique() . This will take left, right
  • if left >= right, then
    • return True
  • counts := a dictionary containing frequencies of each elements present in nums[from index left to right]
  • if minimum frequency from counts > 1, then
    • return False
  • start := left
  • for index in range left to right, do
    • if counts[nums[index]] is same as 1, then
      • if has_unique(start, index - 1) is false, then
        • return False
      • start := index + 1
  • return has_unique(start, right)
  • From the main method, return has_unique(0, size of nums - 1)

Example

Let us see the following implementation to get better understanding −

from collections import Counter
def solve(nums):
   def has_unique(left, right):
      if left >= right:
         return True

      counts = Counter(nums[left : right + 1])
      if min(counts.values()) > 1:
         return False

      start = left

      for index in range(left, right + 1):
         if counts[nums[index]] == 1:
            if not has_unique(start, index - 1):
               return False
            start = index + 1

      return has_unique(start, right)

   return has_unique(0, len(nums) - 1)

nums = [5, 10, 20, 10, 0]
print(solve(nums))

Input

[5, 10, 20, 10, 0]

Output

True

Updated on: 18-Oct-2021

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements