Sum of Floored Pairs - Problem

Given an integer array nums, you need to calculate the sum of all floored divisions between every pair of elements in the array.

More specifically, for every pair of indices i and j where 0 <= i, j < nums.length, compute floor(nums[i] / nums[j]) and sum all these values together.

The floor function returns the largest integer less than or equal to the division result. For example, floor(7/3) = 2 and floor(5/2) = 2.

Important: Since the result can be extremely large, return the answer modulo 109 + 7.

Example: For array [2, 5, 9], we calculate: floor(2/2) + floor(2/5) + floor(2/9) + floor(5/2) + floor(5/5) + floor(5/9) + floor(9/2) + floor(9/5) + floor(9/9) = 1 + 0 + 0 + 2 + 1 + 0 + 4 + 1 + 1 = 10

Input & Output

example_1.py — Basic Case
$ Input: nums = [2, 5, 9]
Output: 10
💡 Note: All pairs: floor(2/2)=1, floor(2/5)=0, floor(2/9)=0, floor(5/2)=2, floor(5/5)=1, floor(5/9)=0, floor(9/2)=4, floor(9/5)=1, floor(9/9)=1. Sum = 1+0+0+2+1+0+4+1+1 = 10
example_2.py — With Duplicates
$ Input: nums = [7, 7, 7, 7, 7, 7, 7]
Output: 49
💡 Note: All 49 pairs (7×7) give floor(7/7) = 1, so the sum is 49 × 1 = 49
example_3.py — Edge Case
$ Input: nums = [1]
Output: 1
💡 Note: Only one pair: floor(1/1) = 1

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • Return result modulo 109 + 7

Visualization

Tap to expand
🍕 Pizza Distribution Calculator2"Small × 35"Medium × 29"Large × 1Calculation Examples:floor(5÷2) × 2 × 3 = 2 × 6 = 12 servingsfloor(9÷5) × 1 × 2 = 1 × 2 = 2 servingsfloor(2÷2) × 3 × 3 = 1 × 9 = 9 servingsWhy This Works:✓ Groups identical calculations✓ Multiplies by frequency counts✓ Avoids redundant divisions✓ Scales with unique values, not total count🎯 Key InsightInstead of calculating each pizza individually (O(n²)),group by size and multiply by quantities (O(k²) where k = unique sizes)
Understanding the Visualization
1
Count Pizza Sizes
Instead of handling each pizza individually, count how many pizzas of each size we have
2
Calculate Serving Ratios
For each unique pizza size pair, calculate how many servings the larger makes from the smaller
3
Multiply by Quantities
Multiply the serving ratio by the count of both pizza sizes
4
Sum All Combinations
Add up all the serving calculations to get the total
Key Takeaway
🎯 Key Insight: By grouping identical values and using frequency multiplication, we transform an O(n²) problem into O(k²) where k is the number of unique elements, providing massive speedup for arrays with duplicates.
Asked in
Google 28 Amazon 22 Meta 15 Microsoft 12
67.2K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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