Sum of Sublist Range Sum - Google Top Interview Questions


Problem Statement :


You are given a list of non-negative integers nums and integers i and j. Let A be a sorted list of the sum of every sublist of nums. Return the sum of A from [i, j], inclusive.

Constraints

1 ≤ n ≤ 100,000 where n is the length of nums

Example 1

Input

nums = [1, 2, 3, 4]

i = 2

j = 3

Output

6

Explanation

A = [1, 2, 3, 3, 4, 5, 6, 7, 9, 10] here and sum([3, 3]) = 6.



Solution :



title-img




                        Solution in C++ :

typedef long long ll;

int solve(vector<int>& nums, int i, int j) {
    int n = nums.size();
    vector<ll> pre(n + 1);
    for (int i = 1; i <= n; ++i) pre[i] = pre[i - 1] + nums[i - 1];
    vector<ll> prepre(n + 1);
    for (int i = 1; i <= n; ++i) prepre[i] = prepre[i - 1] + pre[i];
    auto count = [&](ll sum) {
        ll ans = 0;
        for (int i = 1; i <= n; ++i)
            ans += upper_bound(pre.begin() + i, pre.end(), sum + pre[i - 1]) - (pre.begin() + i);
        return ans;
    };
    auto calc = [&](ll p) {
        ll l = 0, r = pre[n];
        while (l <= r) {
            ll mid = (l + r) >> 1;
            if (count(mid) < p) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        ll smaller = count(l - 1);
        ll equal = p - smaller;
        ll sum = 0;
        for (int i = 1; i <= n; ++i) {
            int pos = upper_bound(pre.begin() + i, pre.end(), pre[i - 1] + l - 1) - pre.begin();
            if (pos > i) sum += prepre[pos - 1] - prepre[i - 1] - pre[i - 1] * (pos - i);
        }
        return sum + equal * l;
    };
    return calc(j + 1) - calc(i);
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int solve(int[] nums, int ii, int jj) {
        int n = nums.length, res = 0, s = 0;
        for (int a : nums) s += a;
        long[] sum = new long[n], sum2 = new long[n];
        sum[0] = sum2[0] = nums[0];
        for (int i = 1; i < n; ++i) {
            sum[i] = sum[i - 1] + nums[i];
            sum2[i] = sum2[i - 1] + sum[i];
        }
        int low = findBound(nums, ii, s), high = findBound(nums, jj, s);
        int countHigh = count(high, nums), countLow = count(low, nums);
        res = low * Math.min(countLow - ii, jj - ii + 1);
        ++low;
        if (low > high)
            return res;
        for (int a = -1, b = -1, k = 0, sa = 0, sb = 0; k < n; ++k) {
            long pre = k > 0 ? sum[k - 1] : 0;
            while (b + 1 < n && sum[b + 1] - pre <= high) ++b;
            while (a < k || (a <= b && sum[a] - pre < low)) ++a;
            if (a <= b) {
                long t = sum2[b] - (a > 0 ? sum2[a - 1] : 0);
                if (k > 0)
                    t -= sum[k - 1] * (b - a + 1);
                res += (int) t;
            }
        }
        if (countHigh > jj + 1)
            res -= high * (countHigh - jj - 1);
        return res;
    }
    private int findBound(int[] ns, int idx, int max) {
        int l = 0, r = max, mid;
        while (l <= r) {
            mid = (l + r) >> 1;
            int t = count(mid, ns);
            if (t >= idx + 1)
                r = mid - 1;
            else
                l = mid + 1;
        }
        return l;
    }
    private int count(int v, int[] ns) {
        int s = 0, res = 0, p = 0;
        for (int i = 0; i < ns.length; ++i) {
            s += ns[i];
            while (s > v && p <= i) {
                s -= ns[p++];
            }
            res += i - p + 1;
        }
        return res;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, nums, i, j):
        n = len(nums)
        a = list(itertools.accumulate([0] + nums))
        b = list(itertools.accumulate([0] + a))

        def cnt(ub):
            c, u = 0, 0
            for v in range(1, n + 1):
                while a[v] - a[u] > ub:
                    u += 1
                c += v - u
            return c

        def go(m):
            lo, hi = 0, a[n]
            while lo < hi:
                mid = (lo + hi) // 2
                if cnt(mid) < m:
                    lo = mid + 1
                else:
                    hi = mid
            s, u = 0, 0
            for v in range(1, n + 1):
                while a[v] - a[u] > lo:
                    u += 1
                s += a[v] * (v - u) - (b[v] - b[u])
            return s - (cnt(lo) - m) * lo

        return go(j + 1) - go(i)
                    


View More Similar Problems

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →