Advertisement

Contains Duplicate - LeetCode 217 Solution

Contains Duplicate - Complete Solution Guide

Contains Duplicate is LeetCode problem 217, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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. Example 1: Input: nums = [1,2,3,1] Output: true Explanation: The element 1 occurs at the indices 0 and 3. Example 2: Input: nums = [1,2,3,4] Output: false Explanation: All elements are distinct. Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true Constraints: 1 <= nums.length <= 10 5 -10 9 <= nums[i] <= 10 9

Detailed Explanation

The problem asks whether an integer array contains any duplicate elements. The input is an array of integers (`nums`). The output is a boolean value: `true` if any element appears at least twice in the array, and `false` otherwise. The constraints specify that the array length can be up to 10<sup>5</sup> elements, and the integer values are within the range -10<sup>9</sup> to 10<sup>9</sup>.

Solution Approach

The provided solutions use a hash set (or unordered_set in C++) to efficiently check for duplicates. The algorithm iterates through the input array. For each element, it checks if the element is already present in the hash set. If it is, a duplicate is found, and `true` is returned. Otherwise, the element is added to the hash set, and the iteration continues. If the loop completes without finding any duplicates, `false` is returned.

Step-by-Step Algorithm

  1. Step 1: Initialize an empty hash set (or set) called `seen`.
  2. Step 2: Iterate through the input array `nums`.
  3. Step 3: For each element `num` in `nums`, check if `num` is present in the `seen` set.
  4. Step 4: If `num` is found in `seen`, return `true` (duplicate found).
  5. Step 5: If `num` is not found in `seen`, add `num` to the `seen` set.
  6. Step 6: After iterating through all elements, return `false` (no duplicates found).

Key Insights

  • Insight 1: Efficiently checking for duplicates requires a data structure that allows for fast lookups (O(1) ideally).
  • Insight 2: A hash table (or set) is an ideal choice because it provides average-case O(1) time complexity for insertion and lookup operations.
  • Insight 3: Sorting the array is an alternative approach, but it increases the time complexity to O(n log n), which is less efficient than the hash table approach for larger datasets.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: Array, Hash Table, Sorting.

Companies

Asked at: Accenture, Airbnb, Arista Networks, DE Shaw, J.P. Morgan, Nagarro, Netflix, Palantir Technologies, Paycom, Siemens, Visa, Yandex, ZScaler, tcs.