How to Detect Duplicate Elements in a PHP Array in O(n) Time
This guide explains how to determine whether an integer array contains any duplicate values by iterating once, using a PHP associative array to track seen elements, and returning true on the first repeat or false if all elements are unique, with detailed code, step‑by‑step flow, and complexity analysis.
Detecting duplicate elements in an array requires scanning each element and checking if it appears more than once. The problem is defined as: given an integer array nums, return true if any value occurs at least twice, otherwise return false.
Example
Input: nums = [1,2,3,1]
Output: true
Input: nums = [1,2,3,4]
Output: falsePHP Solution
The following PHP class implements the required functionality:
class Solution {
/**
* @param Integer[] $nums
* @return Boolean
*/
function containsDuplicate($nums) {
$map = array();
foreach ($nums as $n => $i) {
if (array_key_exists($i, $map)) {
return true;
}
$map[$i] = $n;
}
return false;
}
}Function Execution Flow
Initialize an empty associative array $map to store elements that have been seen.
Iterate over each element $i in $nums.
Check if $i already exists as a key in $map.
If it does, a duplicate is found and the function returns true immediately.
If not, store the element in $map with its index for future checks.
If the loop finishes without finding a duplicate, return false.
Time and Space Complexity
Time complexity: O(n), where n is the number of elements in the input array. Each element is examined once.
Space complexity: O(n) in the worst case, because the associative array may store all unique elements.
Conclusion
The optimized PHP solution leverages an associative array for constant‑time lookups, enabling fast and reliable detection of duplicate values in an array while maintaining linear time and space performance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
