A classic warm-up: does a list of numbers contain the same value twice?
What to build
A program that tells whether any number appears more than once.
Requirements
- Print
yesif some value appears at least twice, otherwiseno. - Aim for one pass over the numbers (O(n)) instead of comparing every pair.
Input
One line of integers separated by spaces.
Output
yes or no.
Constraints
1 ≤ n ≤ 10⁵; each number fits in a normal integer.
Example
Input:
1 2 3 1
Output:
yes
Why it works
A set answers "have I seen this number?" in constant time, so one pass is enough: the first number that is already in the set is a duplicate. Comparing every pair would take O(n²).
Examples
1 2 3 1
yes
1 2 3 4
no
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Say the brute force first: compare every pair, which is O(n²).
Hint 2
A set remembers the numbers seen so far; `x in seen` is O(1).
Hint 3
Stop as soon as you meet a number that is already in the set.
Solution
Show one correct solution (try it yourself first)
nums = input().split()
seen = set()
answer = "no"
for x in nums:
if x in seen:
answer = "yes"
break
seen.add(x)
print(answer)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step