Data Structures & AlgorithmsModerateWipro · Accenture pattern
What is printed? (move zeros to the end keeping order)
What is printed? (move zeros to the end keeping order)
a = [0, 1, 0, 3, 12, 0, 5]
w = 0
for r in range(len(a)):
if a[r] != 0:
a[w], a[r] = a[r], a[w]
w += 1
print(a, w)- A. [1, 3, 12, 5, 0, 0, 0] 3
- B. [1, 3, 12, 5, 0, 0, 0] 4
- C. [1, 3, 5, 12, 0, 0, 0] 4
- D. [5, 12, 3, 1, 0, 0, 0] 4
Correct answer: B. [1, 3, 12, 5, 0, 0, 0] 4
Swapping each non-zero into the write position keeps the relative order of the non-zeros and pushes zeros back. w ends at the number of non-zeros (4). O(n), O(1) extra space, one pass.
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 the time complexity of deleting the last node of a singly linked list of n nodes when only a head pointer is kept?
- A stack is implemented with a singly linked list. Where should push and pop operate to keep both O(1)?
- What is printed? (C strings) c char s[] = "Placement"; printf("%zu %zu", strlen(s), sizeof(s));
- What is printed? (pointer arithmetic on an int array) c int a[] = {10, 20, 30, 40, 50}; int p = a + 1; printf("%d ", (p + 2)); printf("%d…
- What is printed? (2-D array in row-major order) python R, C = 3, 4 base, size = 1000, 4 def addr(i, j, rowmajor=True): return base + size…
- What is printed? (Python string immutability and methods) python s = "Hello World" t = s.replace("o", "0", 1) u = s.swapcase()[::2]…