Skip to content

Instantly share code, notes, and snippets.

@PeculiarE
Created March 12, 2026 22:04
Show Gist options
  • Select an option

  • Save PeculiarE/1da56bc2f7a29c6dd611e09fe90fa6c5 to your computer and use it in GitHub Desktop.

Select an option

Save PeculiarE/1da56bc2f7a29c6dd611e09fe90fa6c5 to your computer and use it in GitHub Desktop.
Fair Candy Swap - LeetCode - Days 71 & 72

Question

Intuition

Using binary search

Approach

Complexity

  • Time complexity: $$O((m+n)\ log\ n)$$

  • Space complexity: $$O(1)$$ (sorting in-place and ignoring the sort's stack space)

Code

class Solution:
    def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
        aliceTotal, bobTotal = sum(aliceSizes), sum(bobSizes)
        bobSizes.sort()
        for aSize in aliceSizes:
            requiredBSize = (bobTotal - aliceTotal + 2 * aSize) // 2
            low, high = 0, len(bobSizes) - 1
            while low <= high:
                mid = (low + high) // 2
                if bobSizes[mid] == requiredBSize:
                    return [aSize, requiredBSize]
                elif bobSizes[mid] < requiredBSize:
                    low = mid + 1
                else:
                    high = mid - 1
        

Result

Screenshot 2026-03-12 at 21 55 31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment