~/problems / Arrays & hashing / Complexity analysis

Cross-team handshake energy

easy ~20 min

At a company mixer, guest i has an energy value energy[i] and belongs to team team[i]. Every two guests from different teams shake hands exactly once, and a handshake between guests i and j produces energy[i] * energy[j] units of buzz. Guests on the same team don't shake hands (they see each other every day).

Write mixer_buzz(energy: list[int], team: list[str]) -> int that returns the total buzz over all cross-team handshakes.

mixer_buzz([2, 3, 5], ["red", "blue", "red"])
# pairs from different teams: (0,1) -> 6, (1,2) -> 15; total 21

mixer_buzz([4, 1], ["ops", "ops"])   # 0, nobody shakes hands
  • 0 <= len(energy) == len(team) <= 2 * 10^5; energies are in [-10^4, 10^4] (negative guests drain the room).
  • Trying every pair is O(n²), about 2 * 10^10 pairs at the maximum size. The tests include a case that size, so aim for O(n).
Show hint

process guests one at a time. When guest j arrives, their new buzz is energy[j] times the total energy of the earlier guests on other teams. How can you get that total in O(1) from sums you keep as you go?

Topic: Complexity analysis. Big-O from constraints: n = 10^5 means O(n log n); know the Python constant factors.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc