↓Skip to main content

Bit-Manipulation

LeetCode 137: Single Number II
·2 mins
LeetCode Medium Array Bit-Manipulation
LeetCode 137 note: with everything else appearing three times, count the 1s at each bit modulo 3; the leftover bits form the answer, minding negatives
LeetCode 287: Find the Duplicate Number
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search Bit-Manipulation
LeetCode 287 note: treat i -> nums[i] as a linked list; the duplicate is the cycle entry, found with Floyd’s algorithm in O(1) space without modifying the array
LeetCode 90: Subsets II
·2 mins
LeetCode Medium Array Backtracking Bit-Manipulation
LeetCode 90 note: sort first; for a number equal to the previous one, extend only the subsets created in the previous step
LeetCode 78: Subsets
·1 min
LeetCode Medium Array Backtracking Bit-Manipulation
LeetCode 78 note: each element is either taken or not; iteratively, each new number copies every existing subset with the number appended
LeetCode 1018: Binary Prefix Divisible By 5
·1 min
LeetCode Easy Array Bit-Manipulation
LeetCode 1018 note: each new bit turns the prefix into x = 2x + bit, so keep only x mod 5 and the number never grows
LeetCode 868: Binary Gap
·2 mins
LeetCode Easy Bit-Manipulation
LeetCode 868 note: remember the last 1’s position and take the maximum distance at each new 1
LeetCode 832: Flipping an Image
·2 mins
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 note: reverse each row and invert its bits, which two pointers can do at once
LeetCode 762: Prime Number of Set Bits in Binary Representation
·1 min
LeetCode Easy Math Bit-Manipulation Primality-Test
LeetCode 762 note: numbers are below 10^6 < 2^20, so the set-bit count is at most 19; check it against a small set of primes
LeetCode 693: Binary Number with Alternating Bits
·1 min
LeetCode Easy Bit-Manipulation
LeetCode 693 note: alternating bits means the binary string has neither 00 nor 11; in bits, n ^ (n » 1) is all ones
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 476: Number Complement
·1 min
LeetCode Easy Bit-Manipulation
LeetCode 476 note: build an all-ones mask as long as num; num ^ mask is the complement
LeetCode 461: Hamming Distance
·1 min
LeetCode Easy Bit-Manipulation
LeetCode 461 note: each 1 in x ^ y is a differing bit, so count the ones