↓Skip to main content
  1. LeetCode/

LeetCode 888: Fair Candy Swap

·2 mins· ·
LeetCode Easy Array Hash-Table Binary-Search Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-21

  • Submissions: Time Limit Exceeded → Wrong Answer ×5 → Runtime Error → Time Limit Exceeded ×2 → Wrong Answer → Accepted → Wrong Answer ×3 → Accepted → Wrong Answer → Runtime Error → Accepted

Approach
#

After Alice gives x and receives y, the totals match: sumA - x + y = sumB - y + x, so y = x + (sumB - sumA) / 2 (Hash Table). Put Bob’s boxes in a set and check y for each x.

My Attempts
#

This took 18 submissions:

  • Attempt 1 recomputed sum(bobSizes) on every iteration and searched a list with in, hitting TLE.
  • Later attempts walked two pointers and adjusted them, never getting the conditions right: indices went out of range or no answer was found, e.g. [4, 8] and [4] (answer [8, 4]). Deriving the formula with a set finally worked.

Solution
#

class Solution:
    def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
        delta = (sum(bobSizes) - sum(aliceSizes)) // 2
        bob = set(bobSizes)
        for x in aliceSizes:
            if x + delta in bob:
                return [x, x + delta]

Complexity
#

Time O(m + n), space O(n).

Mistakes to Avoid
#

  • Derive the formula first instead of recomputing sums inside the loop (O(n) each).
  • An answer is guaranteed, so the difference is even.

Interview Explanation
#

Equal totals after the swap give y = x + (sumB - sumA) / 2, so I put Bob’s sizes in a set and look up y for each x. Time O(m + n).

Related

LeetCode 645: Set Mismatch
·2 mins
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 note: use sums: missing = sum of 1..n - sum of the set, duplicate = array sum - sum of the set
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate
LeetCode 169: Majority Element
·2 mins
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 note: Boyer-Moore voting, where different values cancel in pairs and the survivor is the one appearing more than half the time
LeetCode 594: Longest Harmonious Subsequence
·1 min
LeetCode Easy Array Hash-Table Sliding-Window Sorting
LeetCode 594 note: subsequences need not be contiguous, so just count; for each x add the counts of x and x + 1
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them