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
![Find Duplicate in a list](https://media2.dev.to/dynamic/image/width%3D1000,height%3D500,fit%3Dcover,gravity%3Dauto,format%3Dauto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4gqhadzdja88ve1ys9bv.png)
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
- It initializes an empty dictionary
a
to store numbers encountered so far. - 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.
- If the number is already in
- 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.