Identifying Duplicate Elements in an Array: A PHP Solution
Detecting duplicate elements in an array involves examining each element and checking whether it appears more than once.

Introduction
Given an integer array nums
, return true
if any value appears at least twice in the array, and return false
if every element is distinct.
Examples:
Input: nums = [1,2,3,1]
Output: true
Input: nums = [1,2,3,4]
Output: false
Exploring the Code
Let’s examine the PHP class Solution
and its method containsDuplicate($nums)
:
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;
}
}
How It Works
- Initialization: The function initializes an empty associative array
$map
to store encountered elements and their indices.
2. Duplicate Detection:
- It iterates through each element of the input array
$nums
. - For each element, it checks if it already exists in
$map
. If it does, it means a duplicate element is found, and the function returnstrue
. - If the element doesn’t exist in
$map
, it adds it along with its index to$map
.
3. Return Value: If no duplicate elements are found after iterating through the entire array, the function returns false
.
Time and Space Complexity
Time Complexity: O(n) — where n is the number of elements in the input array. The function iterates through each element of the array once to check for duplicates, resulting in a linear time complexity.
Space Complexity: O(n) — The space used by the associative array ($map) grows linearly with the number of unique elements in the input array. In the worst-case scenario where there are no duplicates, the size of the associative array will be equal to the size of the input array n.
Conclusion
The provided PHP solution efficiently detects duplicate elements in an array using an associative array for storage and constant time lookup.
Happy Coding :)