Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Every value appears three times except one, which appears once. Find it with O(1) extra space.
Problem: Every value appears three times except one, which appears once. Find it with O(1) extra space.
def single(a):
ones = twos = 0
for x in a:
ones = (ones ^ x) & ~twos
twos = (twos ^ x) & ~ones
return ones
print(single([5, 3, 5, 9, 5, 3, 3]), single([-2, -2, 1, -2]))What is printed?- A. 9 -2
- B. 14 1
- C. 9 1
- D. 0 1
Correct answer: C. 9 1
ones and twos form a per-bit counter modulo 3: a bit seen once lives in ones, twice in twos, and the third time clears both. Plain XOR of everything gives 5 ^ 3 ^ 9 here (three copies don't cancel). Works for negatives too. O(n), O(1).
More Coding Interview Problems questions
- Problem: Two values appear once and every other value twice. Find both (smaller first). python def twosingle(a): x = 0 for v in a: x ^= v…
- Problem: Count the bits that differ between two IDs (Hamming distance) and the total over all pairs of an array. python def ham(x, y)…
- Problem: A permissions mask is an int; report how many permissions (set bits) each mask grants. java static int popc(int x) { return…
- Problem: Enumerate all subsets of a small item list using bitmasks and count subsets with even sum. python a = [3, 4, 5, 6] cnt = 0 for…
- Problem: Find the missing number in an array containing n distinct values from 0..n. python def missing(a): x = len(a) for i, v in…
- Problem: Compute 2⁴⁰ mod (10⁹ + 7) by fast power in Java (long arithmetic). java static long power(long b, long e, long m) { long r = 1; b…