Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
What is printed? (finding the k-th node from the end with two pointers)
What is printed? (finding the k-th node from the end with two pointers)
vals = [11, 22, 33, 44, 55, 66]
def kth_end(k):
lead = trail = 0
for _ in range(k):
if lead == len(vals): return None
lead += 1
while lead < len(vals): lead += 1; trail += 1
return vals[trail]
print(kth_end(1), kth_end(4), kth_end(6), kth_end(7))- A. 66 44 11 None
- B. 66 33 11 None
- C. 55 33 11 None
- D. 66 33 11 66
Correct answer: B. 66 33 11 None
Advance the leader k steps, then move both until the leader falls off; the trailer is then k from the end. k = 4 → 33; k = 6 → the first element; k = 7 exceeds the length → None. One pass, 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? (C: array passed to a function decays to a pointer) c void f(int a[]) { printf("%zu ", sizeof(a) / sizeof(a[0])); } int…
- What is printed? (balanced brackets with a counter only) python def bycounter(s): c = 0 for ch in s: c += 1 if ch == '(' else -1 if c < 0…
- What is printed? (string rotation check) python def isrot(a, b): return len(a) == len(b) and b in a + a print(isrot("waterbottle"…
- What is printed? (sliding window: count subarrays with product less than k, positive values) python def countprod(a, k): if k <= 1: return…
- What is printed? (Java: == vs equals on Strings) java String a = "hello"; String b = "hel" + "lo"; String c = new String("hello"); String…
- What is printed? (expected probes in a hash table) python alpha = 0.75 chaining = 1 + alpha / 2 linearhit = 0.5 (1 + 1 / (1 - alpha))…