Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Find the missing number in an array containing n distinct values from 0..n.
Problem: Find the missing number in an array containing n distinct values from 0..n.
def missing(a):
x = len(a)
for i, v in enumerate(a):
x ^= i ^ v
return x
print(missing([3, 0, 1]), missing([9, 6, 4, 2, 3, 5, 7, 0, 1]), missing([0]))What is printed?- A. 2 8 0
- B. 2 8 1
- C. 2 9 1
- D. 4 8 1
Correct answer: B. 2 8 1
XOR all indices 0..n with all values; every present number cancels with its index and the missing one remains. The sum formula n(n+1)/2 − Σa also works but can overflow 32-bit ints for large n in C/Java. O(n), O(1).
More Coding Interview Problems questions
- 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 %…
- Problem: Sum the prices of n = 100000 items, each 50000, in Java. java int n = 100000, price = 50000; int total = n price; long total2 = n…
- Problem: Count primes below n with the sieve of Eratosthenes. python def countprimes(n): if n < 3: return 0 isp = [True] n; isp[0] =…
- Problem: Compute nCr mod p for many queries using precomputed factorials and Fermat inverses (p prime). python M = 109 + 7 N = 20 fact =…
- Problem: Find the GCD of all array elements and the LCM of a pair. cpp long long g(long long a, long long b) { return b == 0 ? a : g(b, a…