Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Two values appear once and every other value twice. Find both (smaller first).
Problem: Two values appear once and every other value twice. Find both (smaller first).
def two_single(a):
x = 0
for v in a: x ^= v
low = x & -x
p = q = 0
for v in a:
if v & low: p ^= v
else: q ^= v
return sorted((p, q))
print(two_single([4, 1, 2, 1, 2, 7, 9, 9]))What is printed?- A. [3, 0]
- B. [4, 7]
- C. [1, 2]
- D. [4, 9]
Correct answer: B. [4, 7]
XOR of all = 4 ^ 7 = 3. Its lowest set bit (1) differs between the two answers, so splitting all values by that bit puts 4 and 7 in different groups, where pairs cancel. O(n), O(1).
More Coding Interview Problems questions
- 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…
- Problem: Sum the remainders of a list of signed deltas modulo 3 in C++ and in Python. cpp int a = -7 % 3; int b = 7 % -3; int c = ((-7 %…