As reported: Microsoft L61 (Jul 2025), round 2 (DSA + functional coding): process a stream of numbers through a set of APIs, one of which returns the sum of the first
nsmallest numbers inO(1); full working code and corner cases were expected.
Implement SmallestSum:
SmallestSum(n)— start with an empty stream;nis fixed.add(num)— a new number arrives.sumSmallest()— return the sum of thensmallest numbers added so far, inO(1)time.
Example 1
SmallestSum(3)
add(5); sumSmallest() -> 5 (fewer than 3 numbers: all of them)
add(1); add(8); sumSmallest() -> 14
add(2); sumSmallest() -> 8 (1 + 2 + 5)
add(0); sumSmallest() -> 3 (0 + 1 + 2)
Example 2
SmallestSum(2)
sumSmallest() -> 0
add(7); add(7); sumSmallest() -> 14
add(7); sumSmallest() -> 14
add(-3); sumSmallest() -> 4
Clarifications
- While fewer than
nnumbers have arrived,sumSmallest()returns the sum of all of them (0for none). - Duplicates count separately.
- The sum can exceed 32 bits: return a 64-bit integer.
Constraints: 1 ≤ n ≤ 10^5; -10^9 ≤ num ≤ 10^9; up to 1.5 · 10^4 calls.
Code runner format: two lines in LeetCode's design format: the method names ("SmallestSum", "add", "sumSmallest") and their arguments. The harness prints the list of return values (null for the constructor and add). Go: Constructor(n), Add, SumSmallest.