Data Structures & AlgorithmsModerateProduct Company SDE pattern
What is printed? (hash set for pairs with a given difference)
What is printed? (hash set for pairs with a given difference)
def pairs_diff(a, k):
s = set(a)
return sorted((x, x + k) for x in s if x + k in s)
print(pairs_diff([1, 7, 5, 9, 2, 12, 3], 2), len(pairs_diff([1, 1, 1, 2], 0)))- A. [(1, 3), (3, 5), (5, 7), (7, 9)] 1
- B. [(1, 3), (5, 7), (7, 9)] 2
- C. [(1, 3), (3, 5), (5, 7), (7, 9), (10, 12)] 2
- D. [(1, 3), (3, 5), (5, 7), (7, 9)] 2
Correct answer: D. [(1, 3), (3, 5), (5, 7), (7, 9)] 2
With k = 2 the distinct pairs are (1,3), (3,5), (5,7), (7,9); 12 − 2 = 10 is absent. For k = 0 the set version is wrong: every distinct value pairs with itself, giving (1,1) and (2,2) = 2, although only 1 has a real duplicate (answer 1). k = 0 needs a count map (values seen at least twice). O(n).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (Python dict ordering and update) python d = {"b": 1, "a": 2} d["c"] = 3 d["b"] = 4 del d["a"] d["a"] = 5…
- What is printed? (prefix sums for range queries) python a = [3, -2, 5, 1, -4, 6] P = [0] for x in a: P.append(P[-1] + x) q = [(0, 2), (1…
- What is printed? (difference array for range increments) python n = 6 diff = [0] (n + 1) for l, r, v in [(0, 2, 5), (1, 4, 3), (3, 5…
- What is printed? (Python sort stability with a key) python recs = [("amit", 82), ("bina", 90), ("chirag", 82), ("dev", 75), ("esha", 90)]…
- What is printed? (finding the k-th node from the end with two pointers) python vals = [11, 22, 33, 44, 55, 66] def kthend(k): lead = trail…
- What is printed? (C: array passed to a function decays to a pointer) c void f(int a[]) { printf("%zu ", sizeof(a) / sizeof(a[0])); } int…