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

Segment Tree

Segment tree can be viewed as an abstract data structure which using some more space to trade for speed. For example, for a typical question with O(N^2) time complexity, the segment tree method can decrease it to O(N*log(N)).  To make it understandable, let us consider one example. Say we have an integer array of N size, and what we want is to query the maximum with a query range [idx1, idx2], where idx1 is the left indexes, and idx2 is the right indexes inclusive. If we only do this kind of query once, then we just need to scan through the array from idx1 to idx2 once, and record the maximum, done. The time complexity is O(N), which is decent enough in most cases even though it is not the optimal one (for example, with a segment tree built, the time complexity can decrease down to O(log(N))). However, how about we need to query the array N times? If we continue to use the naïve way above, then the time complexity is O(N^2), since for each query we need to scan the query range once...

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 ...

Rolling Hash

Rolling hash is one common trick used to increase efficiency of substring comparisons by compressing (or hashing) a string into a integer. After this step, we can compare two strings directly without comparing each chars. So the efficiency can be increased from O(N) to O(1). So how to implement the rolling hash? First we need to choose a base for the expansion and a modulo to mod. The basic formula is (suppose the window is n, and the rolling direction is from left to right), HashVal = (A1*p^(n-1) + A2*p^(n-2) + ... + An-1*p^1 + An*p^0)%mod where HashVal is the hash value, Ai is the ith element, p is the base, and mod is the modulo. To avoid collision as much as we can, p and modulo usually need to be large prime numbers. One corner case is that the base order in the above formula cannot be reversed. Or to be more clear, if the rolling direction is from left to right in an array, the first element should be in the highest order of the base, or times p^(n-1), and the last element times ...