Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: A game keeps scores in a non-decreasing array. Remove duplicates in place and return the number of unique scores.
Problem: A game keeps scores in a non-decreasing array. Remove duplicates in place and return the number of unique scores.
def dedupe(a):
if not a:
return 0
w = 1
for r in range(1, len(a)):
if a[r] != a[w - 1]:
a[w] = a[r]
w += 1
return w, a[:w]
print(dedupe([1, 1, 2, 2, 2, 3, 5, 5]))What is printed?- A. (4, [1, 2, 3, 5])
- B. (5, [1, 2, 3, 5, 5])
- C. (4, [1, 2, 2, 3])
- D. (3, [1, 2, 3])
Correct answer: A. (4, [1, 2, 3, 5])
Slow/fast two pointers: w is the next write slot, r scans. A value is copied only when it differs from the last kept value, giving [1, 2, 3, 5] and count 4. O(n) time, O(1) space.
More Coding Interview Problems questions
- Problem: Allow each value at most twice in a sorted array (in place) and return the new length. python def keep2(a): w = 0 for x in a: if…
- Problem: Two sorted arrays must be merged into the first one, which has spare slots at the end (m real values, n values in the second)…
- Problem: In a sorted array of distinct heights, count pairs (i < j) whose sum is strictly less than a limit. python def pairsbelow(a…
- Problem: Bars of heights h[i] stand at positions i. Pick two bars that hold the most water between them (area = min height × distance)…
- Problem: Find the length of the longest substring of a log line with no repeated character. python def longest(s): last = {} l = best = 0…
- Problem: Find the smallest length of a contiguous block of positive integers whose sum is at least s (0 if none). python def minlen(a, s)…