Complexity and efficiency · 9 / 15 Exercise Medium

First duplicate

Objective

Create a Python program that finds the first repeated element of a list. With two nested loops it is O(n²); with a set (set) it is O(n), because checking whether something is in a set is almost instant.

Instructions

  • Read a line with items separated by spaces (they are text, compared as they are).
  • Go through the list only once storing the seen items in a set. The first duplicate is the first item that, when you reach it, was already in the set.
  • Show First duplicate: X or No duplicates and then Items checked: k with how many items you looked at before stopping (all of them if there are no duplicates).
Input
a b c b a d
Output
First duplicate: b
Items checked: 4

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise