Welcome to another engaging lesson at CodeYourCraft! Today, we're going to dive into a fundamental problem that every programmer faces: Removing Duplicates from an Unsorted List. By the end of this tutorial, you'll not only understand how to tackle this problem but also gain insights into important data structures and algorithms. Let's get started!
An unsorted list contains elements in no particular order. The challenge is to create a program that removes all duplicate values and maintains the order of unique elements.
Before we begin, let's quickly review the two primary types of lists we'll be working with:
numbers = [4, 3, 2, 1, 5, 2, 3, 4, 1, 5, 6]A hash set is a data structure that allows us to store unique elements quickly and efficiently.
unique_numbers = set()for num in numbers:
if num not in unique_numbers:
unique_numbers.add(num)sorted_numbers = list(unique_numbers)Now, sorted_numbers contains the unique elements of the original array, sorted in no particular order.
Quiz What data structure did we use to store unique elements efficiently?
A: Array B: Linked List C: Hash Set Correct: C Explanation: Hash sets allow us to store unique elements quickly and efficiently.
class Node:
def __init__(self, data):
self.data = data
self.next = None
head = Node(4)
node2 = Node(3)
node3 = Node(2)
node4 = Node(1)
node5 = Node(5)
node6 = Node(2)
node7 = Node(3)
node8 = Node(4)
node9 = Node(1)
node10 = Node(5)
node11 = Node(6)
head.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
node6.next = node7
node7.next = node8
node8.next = node9
node9.next = node10
node10.next = node11current = head
previous = Nonewhile current is not None:
if current.next is not None and current.data == current.next.data:
previous.next = current.next.next
else:
previous = current
current = current.nextNow, the linked list contains unique elements.
Quiz What data structure did we use in this example?
A: Array B: Linked List C: Hash Set Correct: B Explanation: We used a Linked List in this example to remove duplicates.
That's it for today! By now, you should have a good understanding of how to remove duplicates from both arrays and linked lists. Keep practicing, and you'll be a data structures and algorithms pro in no time! š
Happy Coding! šØāš»