Skip to main content

Binary Search - Hard Level - Question 1

Binary Search - Hard Level - Question 1


Leetcode 410 Split Array Largest Sum

Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.

Write an algorithm to minimize the largest sum among these m subarrays.

Constraints:

1 <= nums.length <= 1000

0 <= nums[i] <= 10^6

1 <= m <= min(50, nums.length)


Analysis:

This question seems not to be related with binary search, actually it does!

The key argument is: if there is a value, say X, is the minimum of the largest sum among these m non-empty subarrays.  Then all the values below X cannot divide the array into m non-empty subarrays (should be larger than m). 

Why?

We can proof it by contradiction: if a value smaller than X, say Y, can be the minimum of the largest sum among these m non-empty subarrays, then X is NOT the minimum as claimed in the first sentence. Thus, there is no such Y existed.

If all the values smaller than X cannot be the minimum, this question become a typical binary-search problem.

We can make a guessed value, mid,  first. Then we need to divide the array into m non-empty subarrays, and the sum of the each should be <= mid. If there are more subarrays, meaning mid is too smaller, we can remove all the values <= mid out of consideration; otherwise, we can consider a smaller value than mid, to see whether it is still valid, by removing all the values > mid out of consideration.

In addition, the minimum value cannot be smaller than the largest element, since the largest sum of the any non-empty subarray must be >= the largest element. So the largest element gives the left boundary of the binary search.

See the code below:


class Solution {
public:
    int splitArray(vector<int>& nums, int m) {
        int left = 0, right = INT_MAX;
        for(auto &a : nums) left = max(a, left);
        while(left < right) {
            int mid = left + (right - left) / 2;
            if(!isValid(nums, m, mid)) left = mid + 1;
            else right = mid;
        }
        return left;
    }
private:
    bool isValid(vector<int>& nums, int& m, int mid) {
        int ct = 0, sum = 0;
        for(auto &a : nums) {
            sum += a;
            if(sum >= mid) {
                ++ct;
                if(sum > mid) sum = a;
                else sum = 0;
            }
        }
        if(sum > 0) ++ct;
        return ct <= m;
    }
};


Question 2

Leetcode 4 Median of Two Sorted Arrays

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

The overall run time complexity should be O(log (m+n)).

Constraints:

nums1.length == m

nums2.length == n

0 <= m <= 1000

0 <= n <= 1000

1 <= m + n <= 2000

-10^6 <= nums1[i], nums2[i] <= 10^6


Analysis:


One way to think about this question is to find the Kth element of the two SORTED arrays.

We can apply binary search for this: first to make a guess of the value, mid; then count how many elements smaller than mid; if the count < k (the Kth element), we need to make the mid larger (or all the values smaller than mid are NOT valid neither); otherwise, we can test even smaller values (or shrinking the search range to the smaller half range).

For counting, we can use the binary search again, since the array is sorted.


Please see the code below:

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int len1 = nums1.size(), len2 = nums2.size(), sum = len1 + len2;
        if(sum & 1) return findKth(nums1, nums2, sum/2+1)*1.0;
        return (findKth(nums1, nums2, sum/2) + findKth(nums1, nums2, sum/2 + 1))/ 2.0;
    }
    
private:
    int findKth(vector<int> &v1, vector<int> &v2, int k) {
        if(v1.empty()) return v2[k-1];
        if(v2.empty()) return v1[k-1];
        int left = min(v1[0], v2[0]), right = max(v1.back(), v2.back());
        while(left < right) {
            int mid = left + (right - left) / 2;
            int ct = 0;
            auto id1 = upper_bound(v1.begin(), v1.end(), mid) - v1.begin();
            auto id2 = upper_bound(v2.begin(), v2.end(), mid) - v2.begin();
            ct += id1 + id2;
            if(ct < k) left = mid + 1;
            else right = mid;
        }
        return left;
    }
};


The time complexity is O(log(Max-Min) * (log(m) + log(n)))  ~ O(log(m*n)), which may be larger than O(log(m+n)), but they are very close (remember, them are log!). 

This method can be easy to extend to n (>2) sorted arrays to find the median. 

A popular way to reach the literally time complexity of O(log(m+n)) is given below, if interested to check.

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int m = nums1.size(), n = nums2.size(), total = m + n;
        if(total%2==0) return (help(nums1, 0, nums2, 0, total/2) + help(nums1, 0, nums2, 0, total/2+1))/2.0;
        return help(nums1, 0, nums2, 0, total/2+1)/1.0;
    }
private:
    double help(vector<int>& n1, int st1, vector<int>& n2, int st2, int k){
        int m = n1.size() - st1, n = n2.size() - st2;
        if(m > n) return help(n2, st2, n1, st1, k);
        if(m==0) return n2[st2+k-1];
        if(k==1) return min(n1[st1], n2[st2]);
        int a = min(m, k/2), b = k - a;
        if(n1[st1+a-1] == n2[st2+b-1]) return n1[st1+a-1];
        if(n1[st1+a-1] > n2[st2+b-1]) return help(n1, st1, n2, st2+b, k-b);
        return help(n1, st1+a, n2, st2, k-a);
    }
};


Upper Layer

Comments

Popular posts from this blog

Sweep Line

Sweep (or scanning) line algorithm is very efficient for some specific questions involving discrete intervals. The intervals could be the lasting time of events, or the width of a building or an abstract square, etc. In the scanning line algorithm, we usually need to distinguish the start and the end of an interval. After the labeling of the starts and ends, we can sort them together based on the values of the starts and ends. Thus, if there are N intervals in total, we will have 2*N data points (since each interval will contribute 2). The sorting becomes the most time-consuming step, which is O(2N*log(2N) ~ O(N*logN). After the sorting, we usually can run a linear sweep for all the data points. If the data point is labeled as a starting point, it means a new interval is in the processing; when an ending time is reached, it means one of the interval has ended. In such direct way, we can easily figure out how many intervals are in the processes. Other related information can also be obt...

Bit Manipulation - Example

  Leetcode 136 Single Number Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. Constraints: 1 <= nums.length <= 3 * 10^4 -3 * 10^4 <= nums[i] <= 3 * 10^4 Each element in the array appears twice except for one element which appears only once. Analysis: If there is no space limitation, this question can be solved by counting easily. But counting requires additional space. Here we can use xor (^) operation based on some interesting observations:  A^A = 0, here A is any number A^0 = A, here A is any number Since all the number appears twice except one, then all the number appear even numbers will be cancelled out, and only the number appears one time is left, which is what we want. See the code below: class Solution { public: int singleNumber(vector<int>& nums) { int res = 0; for(auto ...

Algorithm Advance Outline

Who wants to read these notes? 1. the one who wants to learn algorithm; 2. the one who has a planned interview in a short amount of time, such as one month later; 3. purely out of curiosity; 4. all the rest. The primary purpose for these posts is to help anyone who wants to learn algorithm in a short amount of time and be ready for coding interviews with tech companies, such as, Amazon, Facebook, Microsoft, etc. Before you start, you are expected to already know:  1. the fundamentals of at least one programming language; 2. the fundamentals of data structures. If you do not have these basics, it is better to "google and read" some intro docs, which should NOT take large amount of time. Of course, you can always learn whenever see a "unknown" data structure or line in the codes. Remember, "google and read" is always one of keys to learning. Common algorithms: 1. Recursion 2. Binary search 3. Dynamic programming 4. Breadth-first search 5. Depth-first search...