Array unique and flip in PHP - Time & Space Complexity
We want to understand how the time needed changes when we use PHP functions to remove duplicates and flip arrays.
How does the work grow as the array gets bigger?
Analyze the time complexity of the following code snippet.
$array = [1, 2, 2, 3, 4, 4, 5];
$unique = array_unique($array);
$flipped = array_flip($unique);
print_r($flipped);
This code removes duplicate values from an array, then swaps keys and values in the resulting array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing the array twice -- once for removing duplicates, once for flipping.
- How many times: Each function loops through the array once, so two passes total.
As the array size grows, the number of steps grows roughly twice as fast because of two passes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 steps (2 x 10) |
| 100 | About 200 steps (2 x 100) |
| 1000 | About 2000 steps (2 x 1000) |
Pattern observation: The work grows linearly with the input size, doubling because of two separate loops.
Time Complexity: O(n)
This means the time needed grows directly in proportion to the number of items in the array.
[X] Wrong: "Using array_unique and array_flip together makes the code run in quadratic time because of nested loops."
[OK] Correct: Each function loops through the array separately, not inside each other, so the total work adds up linearly, not multiplies.
Understanding how built-in functions work under the hood helps you explain your code clearly and shows you know how performance scales with data size.
"What if we replaced array_unique with a manual loop that checks duplicates? How would the time complexity change?"