Bird
Raised Fist0
Interview Prepcyclic-sortmediumAmazonFacebookGoogle

Find All Duplicates in Array

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize variables

We start with the input array and initialize an empty list for duplicates and the index pointer i at 0.

💡 Setting up the initial state is crucial to track progress and store results.
Line:duplicates = [] i = 0 n = len(nums)
💡 We have a pointer i ready to scan the array and a place to collect duplicates.
📊
Find All Duplicates in Array - Watch the Algorithm Execute, Step by Step
Watching each swap and pointer movement reveals how cyclic sort efficiently organizes elements and detects duplicates without extra space.
Step 1/20
·Active fill★Answer cell
setup
i
4
0
3
1
2
2
7
3
8
4
2
5
3
6
1
7
Result: []
compare
i
4
0
3
1
2
2
correct_index
7
3
8
4
2
5
3
6
1
7
Result: []
swap
i
7
0
3
1
2
2
correct_index
4
3
8
4
2
5
3
6
1
7
Result: []
compare
i
7
0
3
1
2
2
4
3
8
4
2
5
correct_index
3
6
1
7
Result: []
swap
i
3
0
3
1
2
2
4
3
8
4
2
5
correct_index
7
6
1
7
Result: []
compare
i
3
0
3
1
correct_index
2
2
4
3
8
4
2
5
7
6
1
7
Result: []
swap
i
2
0
3
1
correct_index
3
2
4
3
8
4
2
5
7
6
1
7
Result: []
compare
i
2
0
correct_index
3
1
3
2
4
3
8
4
2
5
7
6
1
7
Result: []
swap
i
3
0
correct_index
2
1
3
2
4
3
8
4
2
5
7
6
1
7
Result: []
compare
i
3
0
2
1
correct_index
3
2
4
3
8
4
2
5
7
6
1
7
Result: []
move_right
3
0
i
2
1
3
2
4
3
8
4
2
5
7
6
1
7
Result: []
compare
3
0
correct_index
2
1
3
2
4
3
8
4
2
5
7
6
1
7
Result: []
move_right
3
0
2
1
i
3
2
4
3
8
4
2
5
7
6
1
7
Result: []
compare
3
0
2
1
correct_index
3
2
4
3
8
4
2
5
7
6
1
7
Result: []
move_right
3
0
2
1
3
2
i
4
3
8
4
2
5
7
6
1
7
Result: []
traverse
1
0
2
1
3
2
4
3
3
4
2
5
7
6
8
7
Result: []
compare
1
0
2
1
3
2
4
3
i
3
4
2
5
7
6
8
7
Result: []
insert
1
0
2
1
3
2
4
3
3
4
i
2
5
7
6
8
7
Result: [3]
insert
1
0
2
1
3
2
4
3
3
4
2
5
7
6
8
7
Result: [3,2]
record
1
0
2
1
3
2
4
3
3
4
2
5
7
6
8
7
Result: [2,3]

Key Takeaways

✓ Cyclic sort places each number at its correct index, enabling easy detection of duplicates by checking misplaced elements.

This insight is hard to see from code alone because the in-place swaps and pointer logic are subtle without visualization.

✓ Duplicates cause the algorithm to skip swapping and move forward, preventing infinite loops.

Understanding this branching is easier when watching the pointer movement and swap decisions step-by-step.

✓ After sorting, duplicates appear as numbers not matching their index+1, which is a simple and efficient way to identify them.

This final scan is a key step that is easy to overlook when reading code but clear in the visualization.

Practice

(1/5)
1. You are given an unsorted array containing numbers from 1 to n with some numbers possibly missing or duplicated. The task is to rearrange the array so that each number i is placed at index i-1 if it exists. Which algorithmic approach guarantees an optimal O(n) time solution without extra sorting?
easy
A. Use cyclic sort by swapping elements to their correct indices based on their values until all are placed correctly.
B. Sort the array using a built-in sort function and then rearrange elements accordingly.
C. Use dynamic programming to track the placement of each number and build the sorted array.
D. Use a greedy approach that swaps elements to their correct positions until all are placed correctly.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires placing numbers 1 to n at indices 0 to n-1 respectively, handling duplicates or missing numbers efficiently.
  2. Step 2: Identify the optimal approach

    Cyclic sort swaps elements to their correct positions in O(n) time without extra sorting or DP overhead, unlike greedy or sorting approaches.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Cyclic sort directly places elements by index in one pass [OK]
Hint: Cyclic sort swaps elements to correct indices in O(n) time [OK]
Common Mistakes:
  • Confusing greedy swaps with cyclic sort
  • Assuming sorting is always needed
  • Misapplying DP to placement problems
2. You are given an array of n + 1 integers where each integer is between 1 and n (inclusive). Exactly one number is duplicated but may appear multiple times. Which approach guarantees finding the duplicate in O(n) time and O(1) space without modifying the input array?
easy
A. Using a cycle detection algorithm like Floyd's Tortoise and Hare
B. Sorting the array and then scanning for adjacent duplicates
C. Using a hash set to track seen numbers
D. Nested loops comparing every pair of elements

Solution

  1. Step 1: Understand problem constraints

    The array contains n+1 integers with values from 1 to n, guaranteeing at least one duplicate and a cycle in the value-to-index mapping.
  2. Step 2: Identify approach that works without modifying input and uses O(1) space

    Cycle detection (Floyd's Tortoise and Hare) exploits the cycle formed by duplicates and finds the duplicate in linear time and constant space.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Cycle detection fits constraints perfectly [OK]
Hint: Cycle detection finds duplicates without modifying input [OK]
Common Mistakes:
  • Assuming sorting is always optimal despite input modification constraints
  • Using nested loops which are O(n²)
  • Using extra space with hash sets when O(1) space is required
3. You are given an unsorted integer array and need to find the smallest positive integer missing from it in O(n) time and O(1) extra space. Which algorithmic approach best guarantees this optimal solution?
easy
A. Sorting the array and then scanning for the first missing positive
B. Applying a greedy approach to pick the smallest missing positive at each step
C. Using a hash set to track presence of numbers and then scanning from 1 upwards
D. Placing each number in its correct index position using cyclic sort and then scanning

Solution

  1. Step 1: Understand the problem constraints

    The problem requires O(n) time and O(1) space, which rules out sorting (O(n log n)) and hash sets (O(n) space).
  2. Step 2: Identify the approach that rearranges elements in-place

    Cyclic sort places each number in its correct index (number k at index k-1), enabling a linear scan to find the first missing positive efficiently.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Cyclic sort achieves O(n) time and O(1) space [OK]
Hint: Optimal solution uses in-place cyclic sort [OK]
Common Mistakes:
  • Choosing sorting which is O(n log n)
  • Using hash sets which use extra space
  • Greedy approaches that don't guarantee correctness
4. Consider this buggy code snippet for finding missing numbers. Which line contains the subtle bug that can cause infinite loops or incorrect output?
medium
A. Line 3: wrong initialization of n
B. Line 7: incorrect increment of i
C. Line 9: appending missing numbers incorrectly
D. Line 5: missing check before swapping

Solution

  1. Step 1: Identify the missing condition before swap

    The code swaps unconditionally without checking if nums[i] == nums[correct], causing infinite swaps when duplicates exist.
  2. Step 2: Confirm other lines are correct

    Incrementing i only happens in else, missing numbers appended correctly, and n initialized properly.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Missing condition before swap causes infinite loop or wrong placement [OK]
Hint: Check swap condition to avoid infinite loops [OK]
Common Mistakes:
  • Forgetting duplicate check before swap
  • Incrementing i incorrectly
  • Appending indices instead of values
5. Suppose the input array can contain numbers outside the range 1 to n, including negatives and zeros, and duplicates. Which modification to the cyclic sort algorithm ensures correct placement of numbers 1 to n at indices 0 to n-1 while ignoring invalid numbers?
hard
A. Swap elements only if arr[i] is in [1, n] and arr[i] != arr[arr[i] - 1], else increment i.
B. Use an extra array of size n to place valid numbers at index num-1, ignoring invalids.
C. Sort the array first, then remove invalid numbers and duplicates.
D. Ignore duplicates by skipping swaps when arr[i] == arr[arr[i] - 1] without checking range.

Solution

  1. Step 1: Understand input constraints

    Input may have invalid numbers (negatives, zeros, > n) and duplicates that break in-place cyclic sort.
  2. Step 2: Use extra array for placement

    Creating a separate array of size n and placing valid numbers at index num-1 ensures correct placement ignoring invalids and duplicates.
  3. Step 3: Avoid in-place swaps that cause index errors or infinite loops

    Extra space approach is safer and simpler for this variant.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Extra array handles invalid and duplicate numbers cleanly [OK]
Hint: Extra array avoids invalid index and duplicate issues [OK]
Common Mistakes:
  • Ignoring invalid range checks
  • Trying to fix in-place swaps with invalid numbers
  • Not handling duplicates properly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard