Sum of Floored Pairs - 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 10^9 + 7.

The floor() function returns the integer part of the division.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,5,1]
Output: 12
💡 Note: All pairs: floor(2/2)=1, floor(2/5)=0, floor(2/1)=2, floor(5/2)=2, floor(5/5)=1, floor(5/1)=5, floor(1/2)=0, floor(1/5)=0, floor(1/1)=1. Sum = 1+0+2+2+1+5+0+0+1 = 12
Example 2 — Small Array
$ Input: nums = [7,7,7,7,7,7,7]
Output: 49
💡 Note: All elements are 7, so floor(7/7)=1 for all 49 pairs (7×7), giving sum = 49
Example 3 — Edge Case
$ Input: nums = [1,1]
Output: 2
💡 Note: Two pairs: floor(1/1)=1, floor(1/1)=1. Sum = 1+1 = 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Sum of Floored Pairs INPUT nums = [2, 5, 1] 2 i=0 5 i=1 1 i=2 All Pairs (i,j): floor(2/2)=1 floor(2/5)=0 floor(2/1)=2 floor(5/2)=2 floor(5/5)=1 floor(5/1)=5 floor(1/2)=0 floor(1/5)=0 floor(1/1)=1 n = 3, pairs = 9 mod = 10^9 + 7 ALGORITHM STEPS 1 Count Frequency Build count array for each number occurrence 2 Prefix Sum Create prefix sum for range queries 3 Iterate Divisors For each d, find ranges [d*k, d*(k+1)-1] same floor 4 Sum Contributions Add k * count(range) for all valid pairs Calculation: 1+0+2 = 3 (from nums[0]) 2+1+5 = 8 (from nums[1]) 0+0+1 = 1 (from nums[2]) FINAL RESULT Sum all floor divisions: Pair Results Matrix j=0 j=1 j=2 i=0 1 0 2 i=1 2 1 5 i=2 0 0 1 3 + 8 + 1 = 12 Output: 12 OK - Answer verified 12 mod (10^9+7) = 12 Key Insight: For optimal O(n*log(max)) solution: Numbers in range [d*k, d*(k+1)-1] all give floor value k when divided by d. Use prefix sums to count elements in each range efficiently, avoiding O(n^2) brute force approach. Each divisor d contributes: count[d] * sum(k * elements_in_range[d*k, d*(k+1)-1]) for all valid k. TutorialsPoint - Sum of Floored Pairs | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
23.5K Views
Medium Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen