Tuesday, September 19th
Find the duplicate number
Given an array of integers of length n+1, which contains numbers within the range [1,n], and contains on element that is duplicated at least once, find the duplicate element, considering use of only constant space and no changes to the array
The problem of finding duplicates is made difficult by the constraints of no modifications to the original array, and use of only constant extra space. Still, despite these constraints there are still several ways to solve the problem.
Since yesterday's solution involved binary search, we will hone our BS skills by applying it to today's problem
The general idea is based on the observation that without duplicates, the number of elements less than or equal an element is equal to the element itself. E.g., in the collection {1,2,3,4}, the number of elements less than or equal to 2 is 2, less than or equal to 3 is 3, etc.
However, once a duplicate is introduced, the relation is altered for numbers at or above the duplicate
So, we try and find the point where the number of elements less than or greater to an element is greater than the value of the element itself
Rather than iteratively scanning across all elements, we'll use binary search
First we define a function to sum the number of elements less than or equal to a target value. We also define the nums array as global to simplify the function prototype
Then we execute binary search, with our test condition calling the lessOrEqual() function. If the output of lessOrEqual is greater than mid, we know a duplicate occurs somewhere between 1 and mid
Finally, return duplicate
asfd
Comments
Post a Comment