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 the number of unique integers in a sorted list in Python
Finding the number of unique integers in a sorted list is a common programming task. Python provides several efficient approaches to solve this problem, from using built-in data structures to leveraging the sorted nature of 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].
Using Set Data Structure
The most straightforward approach is to use a set to track unique elements ?
def count_unique_with_set(nums):
unique_set = set()
count = 0
for num in nums:
if num not in unique_set:
unique_set.add(num)
count += 1
return count
# Test the function
nums = [3, 3, 3, 4, 5, 7, 7]
result = count_unique_with_set(nums)
print(f"Number of unique elements: {result}")
print(f"Unique elements: {sorted(set(nums))}")
Number of unique elements: 4 Unique elements: [3, 4, 5, 7]
Using Built-in Set Constructor
Python's set constructor provides a more concise solution ?
def count_unique_direct(nums):
return len(set(nums))
# Test with different examples
test_cases = [
[3, 3, 3, 4, 5, 7, 7],
[1, 2, 2, 3, 3, 3, 4],
[5, 5, 5, 5],
[1, 2, 3, 4, 5]
]
for nums in test_cases:
result = count_unique_direct(nums)
print(f"List: {nums}")
print(f"Unique count: {result}")
print()
List: [3, 3, 3, 4, 5, 7, 7] Unique count: 4 List: [1, 2, 2, 3, 3, 3, 4] Unique count: 4 List: [5, 5, 5, 5] Unique count: 1 List: [1, 2, 3, 4, 5] Unique count: 5
Optimized Approach for Sorted Lists
Since the input is sorted, we can optimize by comparing adjacent elements ?
def count_unique_sorted(nums):
if not nums:
return 0
count = 1 # First element is always unique
for i in range(1, len(nums)):
if nums[i] != nums[i-1]:
count += 1
return count
# Test the optimized approach
nums = [3, 3, 3, 4, 5, 7, 7]
result = count_unique_sorted(nums)
print(f"Sorted list: {nums}")
print(f"Unique count: {result}")
# Test with edge cases
edge_cases = [[], [1], [1, 1, 1]]
for case in edge_cases:
print(f"List: {case}, Unique count: {count_unique_sorted(case)}")
Sorted list: [3, 3, 3, 4, 5, 7, 7] Unique count: 4 List: [], Unique count: 0 List: [1], Unique count: 1 List: [1, 1, 1], Unique count: 1
Comparison of Methods
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Set with loop | O(n) | O(n) | General understanding |
| Built-in set | O(n) | O(n) | Concise code |
| Adjacent comparison | O(n) | O(1) | Sorted lists, memory-efficient |
Conclusion
Use len(set(nums)) for the most concise solution. For sorted lists, the adjacent comparison method is memory-efficient with O(1) space complexity. All methods have O(n) time complexity but differ in space usage and readability.
