Data Structures & AlgorithmsModerateProduct Company SDE pattern
What is printed? (two-pointer: remove all occurrences of a value in place)
What is printed? (two-pointer: remove all occurrences of a value in place)
vector<int> a = {3, 2, 2, 3, 4, 3, 5};
int w = 0;
for (int r = 0; r < a.size(); r++)
if (a[r] != 3) a[w++] = a[r];
cout << w << " " << a[0] << a[1] << a[2] << a[3] << " " << a[4] << a[5] << a[6];- A. 4 2245 345
- B. 3 2245 435
- C. 4 2245 435
- D. 4 2245 000
Correct answer: C. 4 2245 435
The write pointer w copies only the kept values: 2, 2, 4, 5 → length 4. The slots after w are NOT cleared – they still hold the old values 4, 3, 5 from positions 4..6. Callers must use only the first w elements. O(n), O(1).
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 printed? (stack: check if a sequence of pops is possible after pushing 1..n in order) python def valid(pushed, popped): st, j =…
- What is printed? (next greater element to the right, −1 if none) python a = [4, 5, 2, 25, 7, 8] res, st = [-1] len(a), [] for i in…
- Hash map counting: what is printed? (first element that repeats, scanning left to right) python def firstrepeat(a): seen = set() for x in…
- What is printed? (anagram check two ways) python from collections import Counter x, y = "listen", "enlists" print(sorted(x) == sorted(y)…
- Binary search: how many iterations does this loop run to find x = 23? python a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] lo, hi, it = 0…
- What is printed? (run-length decode then re-encode) python import re enc = "a3b1c12" dec = "".join(ch int(n) for ch, n in…