Skip to main content
Beginnercoding Verified

Merge three sorted arrays into one sorted array with no duplicate values, writing clean code.

ReportedSource: GeeksforGeeks interview experience: Meta

Quick answer

Three pointers with infinity sentinels for exhausted arrays; take the min, append it only if it differs from the last output, advance every pointer equal to it. Heap for k arrays.

Constraints

  • Input: three groups of numbers, one per line. Each line starts with the length m (0 <= m <= 100000), followed by m integers in non-decreasing order (|value| <= 10^9). Total length at most 100000.
  • Output: the merged values in increasing order, without duplicates, separated by single spaces. Print an empty line if everything is empty.

Sample I/O

in: 3 1 2 3 3 2 3 4 2 3 5

out: 1 2 3 4 5

in: 0 2 1 1 1 1

out: 1

in: 2 -3 -1 2 -2 0 1 5

out: -3 -2 -1 0 5

Loading editor…
Output

Sign up to run your code in the sandbox.

Sign up to run code and get an AI review

You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.

Sign up free

Hints

Reference solution

Three pointers, emit the minimum, skip repeats. Track the last value written so equal values from any array are written once.

main.py
def merge3(a, b, c):
    i = j = k = 0
    out = []
    INF = float('inf')
    while i < len(a) or j < len(b) or k < len(c):
        x = a[i] if i < len(a) else INF
        y = b[j] if j < len(b) else INF
        z = c[k] if k < len(c) else INF
        m = min(x, y, z)
        if not out or out[-1] != m:
            out.append(m)
        if x == m: i += 1
        if y == m: j += 1
        if z == m: k += 1
    return out

Why this stays clean. Using a sentinel for exhausted arrays removes the many special cases that make three-way merges messy, which is exactly what the interviewer in this report watched for. Advancing every pointer equal to the minimum also handles duplicates across arrays.

Complexity. O(n) total time, O(1) extra besides output.

Generalise. For k arrays use a min-heap of (value, array index, element index): O(n log k).

Discussion