How to Detect Duplicate Elements in a PHP Array in O(n) Time

This article explains how to determine whether an integer array contains any duplicate values using a PHP solution that leverages an associative map to achieve linear time and space complexity, complete with example inputs, detailed code walkthrough, and complexity analysis.

php Courses
php Courses
php Courses
How to Detect Duplicate Elements in a PHP Array in O(n) Time

Introduction

Given an integer array nums, the task is to return true if any value appears at least twice and false if every element is unique.

Example

Input: nums = [1,2,3,1]
Output: true

Input: nums = [1,2,3,4]
Output: false

Code Exploration

The PHP class Solution implements the 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;
    }
}

Function Flow

Initialize an empty associative array $map to store encountered elements and their indices.

Iterate over each element of $nums. For each element, check whether its value already exists as a key in $map.

If the key exists, a duplicate is found and the function immediately returns true.

If the key does not exist, store the element in $map for future checks.

After processing all elements 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, because each element is examined exactly once.

Space complexity: O(n), as the associative array may store up to n unique elements in the worst case (when no duplicates exist).

Conclusion

The optimized PHP solution uses an associative array for constant‑time lookups, enabling fast and reliable detection of duplicate elements in an array while maintaining linear time and space efficiency.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithmPHPArrayduplicate detectiontime-complexityspace complexity
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.