Sum of Floored Pairs — LeetCode 1862 Python Solution

HardArrayMathBinary SearchPrefix Sum
Problem
#1862
Pattern
Prefix Sum
Reading time
3 min

The problem

Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 109 + 7.

Example

Input
nums = [2,5,9]
Output
10
Explanation
floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0

Python solution

Python
class Solution:
    def sumOfFlooredPairs(self, nums: List[int]) -> int:
        mod = 10**9 + 7
        cnt = Counter(nums)
        mx = max(nums)
        s = [0] * (mx + 1)
        for i in range(1, mx + 1):
            s[i] = s[i - 1] + cnt[i]
        ans = 0
        for y in range(1, mx + 1):
            if cnt[y]:
                d = 1
                while d * y <= mx:
                    ans += cnt[y] * d * (s[min(mx, d * y + y - 1)] - s[d * y - 1])
                    ans %= mod
                    d += 1
        return ans

Complexity

MeasureComplexity
TimeO(M \times \log M)
SpaceO(M) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1862. Sum of Floored Pairs is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1862. Sum of Floored Pairs?
LeetCode 1862. Sum of Floored Pairs is rated Hard on LeetCode.
What is the time complexity of LeetCode 1862. Sum of Floored Pairs?
The Python solution on this page runs in O(M \times \log M).
What is the space complexity of LeetCode 1862. Sum of Floored Pairs?
The Python solution on this page uses O(M) auxiliary space.
What topics does LeetCode 1862. Sum of Floored Pairs cover?
LeetCode 1862. Sum of Floored Pairs is tagged Array, Math, Binary Search and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview