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

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →