Identifying Duplicate Elements in an Array: A PHP Solution

Athira Radhakrishnan
2 min readMar 27, 2024

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

  1. 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 returns true.
  • 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 :)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Athira Radhakrishnan
Athira Radhakrishnan

Written by Athira Radhakrishnan

Systems Engineer | PHP | SQL | Magento | Aspiring Cybersecurity Student | Professionally active since 2021 | GitHub : https://github.com/AthiraBR

No responses yet

Write a response