Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Two sorted arrays must be merged into the first one, which has spare slots at the end (m real values, n values in the second).
Problem: Two sorted arrays must be merged into the first one, which has spare slots at the end (m real values, n values in the second).
def merge(a, m, b, n):
i, j, k = m - 1, n - 1, m + n - 1
while j >= 0:
if i >= 0 and a[i] > b[j]:
a[k] = a[i]; i -= 1
else:
a[k] = b[j]; j -= 1
k -= 1
return a
print(merge([2, 5, 9, 0, 0, 0], 3, [1, 5, 6], 3))What is printed?- A. [1, 2, 5, 6, 9, 0]
- B. [2, 5, 9, 1, 5, 6]
- C. [1, 2, 5, 5, 6, 9]
- D. [1, 2, 5, 6, 5, 9]
Correct answer: C. [1, 2, 5, 5, 6, 9]
Filling from the back avoids overwriting unread values in a. The loop stops when b is exhausted; leftover a values are already in place. O(m + n), O(1) extra space. Merging from the front would overwrite a[i] before it is read.
More Coding Interview Problems questions
- Problem: In a sorted array of distinct heights, count pairs (i < j) whose sum is strictly less than a limit. python def pairsbelow(a…
- Problem: Bars of heights h[i] stand at positions i. Pick two bars that hold the most water between them (area = min height × distance)…
- Problem: Find the length of the longest substring of a log line with no repeated character. python def longest(s): last = {} l = best = 0…
- Problem: Find the smallest length of a contiguous block of positive integers whose sum is at least s (0 if none). python def minlen(a, s)…
- Problem: A binary array may have at most k zeros flipped to 1. Return the longest run of 1s achievable. python def longestones(a, k): l =…
- Problem: Return the maximum of every window of size k in a stream of readings. python from collections import deque def winmax(a, k): dq…