Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (Josephus recurrence)
What is printed? (Josephus recurrence)
def josephus(n, k):
r = 0
for m in range(2, n + 1):
r = (r + k) % m
return r + 1
print(josephus(7, 3), josephus(10, 2), josephus(1, 5))- A. 4 4 1
- B. 4 5 1
- C. 3 5 1
- D. 4 5 0
Correct answer: B. 4 5 1
J(1) = 0 and J(m) = (J(m − 1) + k) mod m (0-based); add 1 for 1-based positions. n = 7, k = 3 → 4; n = 10, k = 2 → 5 (also 2·(10 − 8) + 1). O(n) instead of simulating the circle in O(nk).
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? (hash set for pairs with a given difference) python def pairsdiff(a, k): s = set(a) return sorted((x, x + k) for x in s…
- 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…