Detecting Duplicate Elements in an Array Using PHP
This article explains how to determine whether an integer array contains duplicate values by traversing the array with a PHP solution that uses an associative map, and it details the algorithm's execution flow, time and space complexity, and provides sample inputs and outputs.
Introduction
Detecting duplicate elements in an array requires traversing each element and checking whether any value appears more than once, ensuring that no possible duplicate is missed.
Problem Description
Given an integer array nums , return true if any value appears at least twice; otherwise return false when every element is unique.
Example
Input: nums = [1,2,3,1]
Output: true
Input: nums = [1,2,3,4]
Output: falseExploring the Code
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
1. Initialization : The function creates an empty associative array $map to store elements and their indices.
2. Duplicate Detection :
The function iterates over each element in $nums .
For each element, it checks whether the element already exists as a key in $map .
If it exists, a duplicate has been found and the function immediately returns true .
If it does not exist, the element and its index are added to $map for future checks.
3. Return Value : After scanning the entire array without finding duplicates, the function returns false , indicating that the array contains only unique elements.
Time and Space Complexity
Time complexity: O(n) , where n is the number of elements in the input array, because each element is examined once.
Space complexity: O(n) , as the associative array $map may store up to n entries in the worst case (when no duplicates exist).
Conclusion
The optimized PHP solution leverages an associative array for constant‑time lookups, enabling fast and reliable detection of duplicate elements while maintaining linear time and space performance.
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.