Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: In an array every value appears twice except two values that appear once. Find those two in O(n) time and O(1) space.
Problem: In an array every value appears twice except two values that appear once. Find those two in O(n) time and O(1) space.
def two(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([4, 1, 2, 1, 2, 3, 5, 5, 6, 6]))What is printed?- A. 4 7
- B. 1 3
- C. 3 4
- D. 3 5
Correct answer: C. 3 4
XOR of everything is 4 ^ 3 = 7; its lowest set bit (1) differs between the two singles. Splitting by that bit puts 1, 1, 3, 5, 5 in one group (XOR = 3) and 4, 2, 2, 6, 6 in the other (XOR = 4).
More Coding Interview Problems questions
- Building a binary heap from n given keys: what are the worst-case costs of (i) bottom-up heapify and (ii) n successive inserts into an…
- In Java 8+, many keys that are Comparable and all land in ONE HashMap bucket. What is the worst-case cost of get() on that bucket once it…
- Problem: For each day, how many days until a strictly warmer day (0 if none)? python def wait(t): res, st = [0] len(t), [] for i, x in…
- Problem: The span of a stock on a day is the number of consecutive days up to and including it with price ≤ that day's price. python def…
- Problem: Asteroids move along a line: positive = right, negative = left, |value| = size. When two meet, the smaller explodes; equal sizes…
- Problem: Decode a string where k[s] means s repeated k times (brackets can nest). python def decode(s): st, cur, k = [], "", 0 for c in s…