Tutorialspoint
Problem
Solution
Submissions

Remove Duplicates from a List

Certification: Basic Level Accuracy: 85.37% Submissions: 41 Points: 5

Write a Python program that removes all duplicate elements from a given list while preserving the original order.

Example 1
  • Input: list = [1, 2, 3, 1, 2, 5, 6, 7, 8, 6]
  • Output: [1, 2, 3, 5, 6, 7, 8]
  • Explanation:
    • Step 1: Iterate through the original list, keeping track of elements seen so far.
    • Step 2: For each element, if it hasn't been seen before, add it to the result list.
    • Step 3: If the element has been seen before, skip it.
    • Step 4: Return the result list containing only the first occurrence of each element.
Example 2
  • Input: list = [10, 20, 30, 40, 50]
  • Output: [10, 20, 30, 40, 50]
  • Explanation:
    • Step 1: Iterate through the original list.
    • Step 2: Since all elements are unique, each element is added to the result list.
    • Step 3: The resulting list remains the same as the input list.
Constraints
  • 1 ≤ list_length ≤ 10^6
  • -10^9 ≤ list[i] ≤ 10^9
  • Time Complexity: O(n) where n is the length of the input list
  • Space Complexity: O(n) to store the unique elements
SetListTech MahindraDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a set to track seen elements
  • Iterate through the list once
  • Add elements to the result list only if not seen before

Steps to solve by this approach:

 Step 1: Initialize an empty set to track seen elements.

 Step 2: Create an empty list to store the result with duplicates removed.
 Step 3: Iterate through each element in the input list.
 Step 4: Check if the element has been seen before.
 Step 5: If the element is not in the seen set, add it to both the set and result list.
 Step 6: Return the list with duplicates removed while preserving original order.

Submitted Code :