Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.
Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.
Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.
Example 1:
Input: aliceSizes = [1,1], bobSizes = [2,2] Output: [1,2]
Example 2:
Input: aliceSizes = [1,2], bobSizes = [2,3] Output: [1,2]
Example 3:
Input: aliceSizes = [2], bobSizes = [1,3] Output: [2,3]
Constraints:
1 <= aliceSizes.length, bobSizes.length <= 1041 <= aliceSizes[i], bobSizes[j] <= 105Problem summary: Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Binary Search
[1,1] [2,2]
[1,2] [2,3]
[2] [1,3]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #888: Fair Candy Swap
class Solution {
public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
int s1 = 0, s2 = 0;
Set<Integer> s = new HashSet<>();
for (int a : aliceSizes) {
s1 += a;
}
for (int b : bobSizes) {
s.add(b);
s2 += b;
}
int diff = (s1 - s2) >> 1;
for (int a : aliceSizes) {
int b = a - diff;
if (s.contains(b)) {
return new int[] {a, b};
}
}
return null;
}
}
// Accepted solution for LeetCode #888: Fair Candy Swap
func fairCandySwap(aliceSizes []int, bobSizes []int) []int {
s1, s2 := 0, 0
s := map[int]bool{}
for _, a := range aliceSizes {
s1 += a
}
for _, b := range bobSizes {
s2 += b
s[b] = true
}
diff := (s1 - s2) / 2
for _, a := range aliceSizes {
if b := a - diff; s[b] {
return []int{a, b}
}
}
return nil
}
# Accepted solution for LeetCode #888: Fair Candy Swap
class Solution:
def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
diff = (sum(aliceSizes) - sum(bobSizes)) >> 1
s = set(bobSizes)
for a in aliceSizes:
if (b := (a - diff)) in s:
return [a, b]
// Accepted solution for LeetCode #888: Fair Candy Swap
struct Solution;
use std::collections::HashSet;
impl Solution {
fn fair_candy_swap(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> {
let sum_a: i32 = a.iter().sum();
let sum_b: i32 = b.iter().sum();
let hs: HashSet<i32> = b.into_iter().collect();
for x in a {
let y = x + (sum_b - sum_a) / 2;
if hs.contains(&y) {
return vec![x, y];
}
}
unreachable!();
}
}
#[test]
fn test() {
let a = vec![1, 2];
let b = vec![2, 3];
let res = vec![1, 2];
assert_eq!(Solution::fair_candy_swap(a, b), res);
let a = vec![2];
let b = vec![1, 3];
let res = vec![2, 3];
assert_eq!(Solution::fair_candy_swap(a, b), res);
let a = vec![1, 2, 5];
let b = vec![2, 4];
let res = vec![5, 4];
assert_eq!(Solution::fair_candy_swap(a, b), res);
}
// Accepted solution for LeetCode #888: Fair Candy Swap
function fairCandySwap(aliceSizes: number[], bobSizes: number[]): number[] {
const s1 = aliceSizes.reduce((acc, cur) => acc + cur, 0);
const s2 = bobSizes.reduce((acc, cur) => acc + cur, 0);
const diff = (s1 - s2) >> 1;
const s = new Set(bobSizes);
for (const a of aliceSizes) {
const b = a - diff;
if (s.has(b)) {
return [a, b];
}
}
return [];
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.