Was it helpful?

Question

Program to find the number of unique integers in a sorted list in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of sorted numbers called nums we have to find the number of unique elements in the list.

So, if the input is like nums = [3, 3, 3, 4, 5, 7, 7], then the output will be 4, as The unique numbers are [3, 4, 5, 7]

To solve this, we will follow these steps −

  • s:= a new set
  • cnt:= 0
  • for each i in nums, do
    • if i is not in s, then
      • insert i into s
      • cnt := cnt + 1
  • return cnt

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      s=set()
      cnt=0
      for i in nums:
         if i not in s:
            s.add(i)
            cnt += 1
      return cnt
ob = Solution()
print(ob.solve([3, 3, 3, 4, 5, 7, 7]))

Input

[3, 3, 3, 4, 5, 7, 7]

Output

4
raja
Published on 05-Oct-2020 11:21:16
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top