Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Move all zero readings to the end of the array in place while keeping the order of the non-zero readings.
Problem: Move all zero readings to the end of the array in place while keeping the order of the non-zero readings.
def move_zeros(a):
w = 0
for x in a:
if x != 0:
a[w] = x; w += 1
for i in range(w, len(a)):
a[i] = 0
return a
print(move_zeros([0, 5, 0, 0, 3, 8, 0, 1]))What is printed?- A. [0, 0, 0, 0, 5, 3, 8, 1]
- B. [5, 3, 8, 1]
- C. [1, 8, 3, 5, 0, 0, 0, 0]
- D. [5, 3, 8, 1, 0, 0, 0, 0]
Correct answer: D. [5, 3, 8, 1, 0, 0, 0, 0]
A write pointer w copies each non-zero value to the next free slot (stable), then the tail is filled with zeros. Order 5, 3, 8, 1 is preserved. O(n) time, O(1) extra space; swapping from both ends would be O(n) too but breaks the relative order.
More Coding Interview Problems questions
- Problem: In a text editor '#' means backspace (on an empty buffer it does nothing). Compute the final text with a stack. python def…
- Problem: Normalise a Unix-style absolute path: collapse repeated slashes, drop '.', and let '..' go up one directory (never above root)…
- Problem: Find the minimum number of brackets to insert so that a string of '(' and ')' becomes balanced. python def minadd(s): open = add…
- Problem: Parcels 1..5 are pushed onto a loading stack in that order (pops may happen at any time). Decide whether a given pop order is…
- Problem: People queue at a single counter; person i wants t[i] tickets, buys one per second and, if still needing more, goes to the back…
- Problem: Regroup a linked list so that all nodes at odd positions (1st, 3rd, …) come first, followed by the even positions, keeping…