Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Sort an array of 0s, 1s and 2s in one pass (Dutch national flag).
Problem: Sort an array of 0s, 1s and 2s in one pass (Dutch national flag).
void sort012(vector<int>& a) {
int lo = 0, mid = 0, hi = a.size() - 1;
while (mid <= hi) {
if (a[mid] == 0) swap(a[lo++], a[mid++]);
else if (a[mid] == 1) mid++;
else swap(a[mid], a[hi--]); // mid is NOT advanced
}
}
// a = {2, 0, 2, 1, 1, 0}What is a after the call?- A. 0 0 1 2 1 2
- B. 0 1 0 1 2 2
- C. 0 0 1 1 2 2
- D. 2 2 1 1 0 0
Correct answer: C. 0 0 1 1 2 2
Invariant: [0, lo) holds 0s, [lo, mid) 1s, (hi, end] 2s. After swapping a 2 to the back, the element brought to mid is unexamined, so mid must stay – advancing it is the classic bug that leaves a 2 or 0 misplaced. One pass, O(1) space.
More Coding Interview Problems questions
- Problem: Find the next lexicographic permutation of a digit list in place. python def nextperm(a): i = len(a) - 2 while i >= 0 and a[i] >=…
- Problem: Count pairs of songs whose total duration is divisible by 60. python def pairs60(t): cnt = [0] 60; res = 0 for x in t: r = x % 60…
- Problem: Find the length of the longest subarray with equal numbers of 0s and 1s. python def longesteq(a): first = {0: -1}; bal = best = 0…
- Problem: Find all elements that appear more than ⌊n/3⌋ times. python def overthird(a): c1 = c2 = None; n1 = n2 = 0 for x in a: if x == c1…
- Problem: Find the length of the shortest unsorted continuous subarray which, if sorted, makes the whole array sorted. python def…
- Problem: Compute the amount of rain water trapped between bars. python def trap(h): l, r = 0, len(h) - 1; lm = rm = water = 0 while l < r…