Find Duplicate in a list

The findDuplicate function is designed to find the first duplicate number in a list. Here's a concise breakdown: Code Explanation class Solution(object): def findDuplicate(self, nums): a = {} # Dictionary to store encountered numbers i = 0 while i

Feb 5, 2025 - 17:45
 0
Find Duplicate in a list

The findDuplicate function is designed to find the first duplicate number in a list. Here's a concise breakdown:

Code Explanation

class Solution(object):
    def findDuplicate(self, nums):
        a = {}  # Dictionary to store encountered numbers
        i = 0
        while i < len(nums):  # Loop through the list
            if nums[i] in a:  # If the number is already in the dictionary, it's a duplicate
                return nums[i]  # Return the duplicate number
            else:
                a[nums[i]] = 1  # Mark the number as seen
            i += 1  # Move to the next number

How It Works

  1. It initializes an empty dictionary a to store numbers encountered so far.
  2. It loops through the list nums:
    • If the number is already in a, it returns that number as the first duplicate.
    • Otherwise, it adds the number to a and continues.
  3. The function returns the first duplicate found in the list.

Example

Input:

nums = [1, 3, 4, 2, 2]
solution = Solution()
print(solution.findDuplicate(nums))

Output:

2

Explanation:

  • The number 2 appears twice in the list, and the function detects it as the first duplicate.