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?
  1. A. (4, [1, 2, 3, 5])
  2. B. (5, [1, 2, 3, 5, 5])
  3. C. (4, [1, 2, 2, 3])
  4. 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

Exams that ask this topic