minimanimoh / Udacity_DS-A

0 stars 0 forks source link

DS&A - 2. Data Structures - Lesson 1. Duplicate Number #4

Closed minimanimoh closed 3 years ago

minimanimoh commented 3 years ago

Problem You have been given an array of length = n. The array contains integers from 0 to n - 2. Each number in the array is present exactly once except for one number which is present twice. Find and return this duplicate number present in the array.

solution

def duplicate_number(arr):
    current_sum = 0
    expected_sum = 0

    for num in arr:
        current_sum += num

    for i in range(len(arr) - 1):
        expected_sum += i
    return current_sum - expected_sum

my code

def duplicate_number(arr):
    arr = sorted(arr)
    for i in range(len(arr)):
        while arr[i] == arr[i + 1]:
            return arr[i]
minimanimoh commented 3 years ago

Solution: difference of each of the total sum My code: sorted out for ascending order and found the same number