Workspace Contains Duplicate
0d
DSA Problem Sheet

Contains Duplicate

Return 1 as soon as an integer occurs a second time, otherwise return 0.

EXECUTION LAB

Return 1 as soon as an integer occurs a second time, otherwise return 0.

Input and constraints
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
seen = [0] * (2001)
i = 0
while (i < len(values)):
key = (values[i] + 1000)
if (seen[key] == 1):
return 1
seen[key] = 1
i = (i + 1)
return 0

Visualizer

Step 1 of 5
04i
1-2
21
3-2

Inspect the current state

Check whether this value already owns a marked entry.

Variable watch

i 0key 1004

Step explanation

Check whether this value already owns a marked entry.

comparisons 1reads 1writes 0swaps 0recursiveCalls 0
Educational simulation · O(n + U), U = 2001 time · O(U) space

Worked explanation

Cross off a roll number on first attendance. An already crossed number signals a repeat.

Guided solution

Use the bounded value range to keep a presence table.

O(n + U), U = 2001 time · O(U) auxiliary space

Examples

Worked example · {"values":[4,-2,1,-2],"target":0} ⇒ 1

Edge case 1 · {"values":[],"target":0} ⇒ 0

Edge case 2 · {"values":[5,6],"target":0} ⇒ 0

Progressive hints

Hint 1Cross off a roll number on first attendance. An already crossed number signals a repeat.
Hint 2Use the bounded value range to keep a presence table.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Negative numbers require an offset before indexing the table.

Interview follow-up

What structure would support arbitrary strings?