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

"How They Met Themselves" by Dante Rossetti, depicting doppelgängers

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

vector<int> nums;

int lessOrEqual(int val) {
int count=0;
for(int i=0; i<nums.size(); i++) {
if(nums[i]<=val) count++;
}
return count;
}
 
    int findDuplicate(vector<int>& nums) {
this->nums=nums;
        ...
    }

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

    int low=1, high=nums.size();
int duplicate=-1;
while (low<=high) {
int mid=(low+high)/2;
if(small_or_equal(mid)>mid) {
duplicate=mid;
high=mid-1;
} else {
low=mid+1;
}
}

Finally, return duplicate

    int findDuplicate(vector<int>& nums) {
        ...
        return duplicate;
}

asfd

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th