Hackerrank Algorithms 3 ā Questions and Answers
Question 1: What is the output of `list(map(lambda x: x**2, [1, 2, 3, 4]))`?
- [1, 4, 9, 16] (Correct answer)
- [2, 4, 6, 8]
- [1, 2, 3, 4]
- [1, 8, 27, 64]
Correct answer: [1, 4, 9, 16]
`map` applies the lambda squaring function to each element, producing [1, 4, 9, 16].
Question 2: Which traversal of a binary tree visits nodes in the order: left subtree, root, right subtree?
- Pre-order
- Post-order
- In-order (Correct answer)
- Level-order
Correct answer: In-order
In-order traversal follows left ā root ā right, which visits BST nodes in sorted order.
Question 3: What Python built-in can find the greatest common divisor of two integers?
- math.gcd(a, b) (Correct answer)
- math.lcm(a, b)
- int.gcd(a, b)
- fractions.gcd(a, b)
Correct answer: math.gcd(a, b)
`math.gcd(a, b)` computes the greatest common divisor using the Euclidean algorithm.
Question 4: A sliding window of size k moves across an array of size n. What is the total number of windows?
- k
- n
- n - k + 1 (Correct answer)
- n * k
Correct answer: n - k + 1
The first window starts at index 0 and the last at index n-k, giving n-k+1 total windows.
Question 5: What does `heapq.nlargest(3, [5, 1, 8, 3, 9, 2])` return?
- [1, 2, 3]
- [9, 8, 5] (Correct answer)
- [5, 8, 9]
- [9, 8, 3]
Correct answer: [9, 8, 5]
`heapq.nlargest(k, iterable)` returns the k largest elements in descending order.
Question 6: Which sorting algorithm has the best average-case and worst-case time complexity of O(n log n)?
- Quicksort
- Bubble Sort
- Merge Sort (Correct answer)
- Insertion Sort
Correct answer: Merge Sort
Merge sort always divides and merges in O(n log n) regardless of input, unlike quicksort which degrades to O(n²).
Question 7: In Python, what is the result of `[x for x in range(10) if x % 2 == 0]`?
- [1, 3, 5, 7, 9]
- [0, 2, 4, 6, 8] (Correct answer)
- [0, 1, 2, 3, 4]
- [2, 4, 6, 8, 10]
Correct answer: [0, 2, 4, 6, 8]
The list comprehension filters range(10) for even numbers (remainder 0 when divided by 2).
What is the output of `list(map(lambda x: x**2, [1, 2, 3, 4]))`?