Workspace Remove Duplicates From Sorted Array
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Compress Sorted Values visualizer

Return the distinct values of the sorted input in their original order.

EXECUTION LAB

Return the distinct values of the sorted input in their original order.

Input and constraints
  • Values must be in nondecreasing order.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
count = 0
i = 0
while (i < len(values)):
if ((i == 0) or (values[i] != values[(i - 1)])):
count = (count + 1)
i = (i + 1)
out = [0] * (count)
i = 0
write = 0
while (i < len(values)):
if ((i == 0) or (values[i] != values[(i - 1)])):
out[write] = values[i]
write = (write + 1)
i = (i + 1)
return out

Visualizer

Step 1 of 9
01i
11
22
34
44

Identify a run start at position the current value

Identify a run start at position 0.

Variable watch

i 0count 0

Step explanation

Identify a run start at position 0.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(u) output for u distinct values space

Worked explanation

A class register needs one entry per group of identical name tags.

Guided solution

Count and copy run starts; every different value starts a new run.

O(n) time · O(u) output for u distinct values auxiliary space

Examples

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

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

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

Progressive hints

Hint 1A class register needs one entry per group of identical name tags.
Hint 2Count and copy run starts; every different value starts a new run.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

An empty sequence contains zero distinct values.

Interview follow-up

How could you compact the original array using a write pointer?

Continue learning

Practice related DSA questions in the same topic.