Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Return the squares of a sorted array (values may be negative) in non-decreasing order in O(n), filling the result from the back with two pointers.
Problem: Return the squares of a sorted array (values may be negative) in non-decreasing order in O(n), filling the result from the back with two pointers.
def sorted_squares(a):
n = len(a); res = [0] * n
l, r, k = 0, n - 1, n - 1
while l <= r:
if abs(a[l]) > abs(a[r]):
res[k] = a[l] * a[l]; l += 1
else:
res[k] = a[r] * a[r]; r -= 1
k -= 1
return res
print(sorted_squares([-7, -3, 2, 3, 11]))What is printed?- A. [121, 49, 9, 9, 4]
- B. [4, 9, 9, 49, 121]
- C. [4, 9, 49, 121]
- D. [49, 9, 4, 9, 121]
Correct answer: B. [4, 9, 9, 49, 121]
The largest square is always at one of the two ends (most negative or most positive), so compare |a[l]| and |a[r]| and write the bigger square into the last free slot. Order of writes: 121, 49, 9 (from 3), 9 (from −3), 4. Squaring in place without re-sorting would leave [49, 9, 4, 9, 121]. O(n) time, O(n) output.
More Coding Interview Problems questions
- Problem: A wallet starts with a positive balance s and then applies the day's changes in order. Find the minimum s such that the running…
- Problem: A warehouse aisle has shelves with weights; find the leftmost 'balance shelf' i such that the total weight strictly to its left…
- Problem: A street has n = 6 lamps, all starting at brightness 0. Each command (l, r, v) adds v to every lamp from l to r (0-based…
- Problem: A 3 × 4 grid of crop yields must answer 'total yield in rectangle (r1, c1)–(r2, c2)' in O(1) using a 2-D prefix table with one…
- Problem: Find the total of the sums of ALL contiguous subarrays without enumerating them: element a[i] lies in (i + 1)·(n − i) subarrays…
- Problem: A login service flags an account if the same device ID appears twice within at most k positions of the access log (|i − j| ≤ k)…