Compute the required size difference, store one person's sizes in a set, and find a pair satisfying the balance equation.
Complexity
O(n + m) expected time and O(m) space.
Find one candy-size exchange that makes two people's total candy amounts equal.
Compute the required size difference, store one person's sizes in a set, and find a pair satisfying the balance equation.
O(n + m) expected time and O(m) space.
package main
func fairCandySwap(aliceSizes []int, bobSizes []int) []int {
aliceTotal, bobTotal := 0, 0
bobSet := map[int]bool{}
for _, value := range aliceSizes {
aliceTotal += value
}
for _, value := range bobSizes {
bobTotal += value
bobSet[value] = true
}
difference := (aliceTotal - bobTotal) / 2
for _, alice := range aliceSizes {
if bobSet[alice-difference] {
return []int{alice, alice - difference}
}
}
return nil
}
class Solution:
def fairCandySwap(self, aliceSizes: list[int], bobSizes: list[int]) -> list[int]:
difference = (sum(aliceSizes) - sum(bobSizes)) // 2
bob_set = set(bobSizes)
for alice in aliceSizes:
if alice - difference in bob_set: return [alice, alice - difference]
return []
function fairCandySwap(aliceSizes: number[], bobSizes: number[]): number[] {
const aliceTotal = aliceSizes.reduce((sum, value) => sum + value, 0);
const bobTotal = bobSizes.reduce((sum, value) => sum + value, 0);
const bobSet = new Set(bobSizes);
const difference = (aliceTotal - bobTotal) / 2;
for (const alice of aliceSizes) if (bobSet.has(alice - difference)) return [alice, alice - difference];
return [];
}