Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Every number in a list of sensor IDs appears twice except one. Find the lonely ID in O(n) time and O(1) space.
Problem: Every number in a list of sensor IDs appears twice except one. Find the lonely ID in O(n) time and O(1) space.
def lonely(a):
r = 0
for x in a:
r ^= x
return r
print(lonely([14, 7, 9, 14, 3, 9, 7]))What is printed?- A. 14
- B. 0
- C. 3
- D. 7
Correct answer: C. 3
XOR is associative and x ^ x = 0, so every paired value cancels and only 3 survives. O(n) time, O(1) space; a hash-count solution also works but needs O(n) space.
More Coding Interview Problems questions
- Problem: Return, for every index i, the product of all elements except a[i], without using division. Example: [1, 2, 3, 4] → [24, 12, 8…
- Problem: Given an array where values lie in 1..n, find the value that appears twice (exactly one does) without modifying the array. python…
- Problem: Given n ≤ 10⁵ integers (not sorted), find the length of the longest run of consecutive values, e.g. [100, 4, 200, 1, 3, 2] → 4…
- Problem: Group words that are anagrams of each other and report how many groups there are. python from collections import defaultdict def…
- Problem: Count the number of contiguous subarrays whose sum equals k. Values can be negative. python def countk(a, k): seen = {0: 1} p =…
- Problem: Count subarrays whose sum is divisible by k (values may be negative). python def divk(a, k): cnt = [0] k cnt[0] = 1 p = ans = 0…