Union of two sorted arrays MEDIUM Interclasare (BAC) 25 XP 0 solved
Mobile coding works. A laptop is faster for long sessions.

Problem

Two arrays of integers `a` and `b` are given, both already sorted in non-decreasing order (possibly with repeated values within the same array). Construct, by merging, the array of their union: a sorted array containing each value that appears in `a` or in `b` exactly once (no duplicates). The required algorithm is the classic two-pointer merge, in which, before adding a new value to the result, you check whether it is already equal to the last written value.

Input format

Input input.txt

The program reads from standard input: - a natural number `n`, followed by `n` integers (array `a`, sorted in non-decreasing order); - a natural number `m`, followed by `m` integers (array `b`, sorted in non-decreasing order). - `1 <= n, m <= 1000` - `-1000000 <= values <= 1000000` - the arrays are sorted in non-decreasing order but may contain duplicates

Output format

Output output.txt

The program prints on the first line the number `k` of distinct values in the union, and on the second line the `k` values in non-decreasing order, separated by a single space. Both lines end with a newline.

Example

input
5
1 3 5 7 9
4
2 4 6 8
output
9
1 2 3 4 5 6 7 8 9

Ready to solve this challenge?

Create a free account to write code, submit solutions, and track your progress.

⌨️ Keyboard Shortcuts

Code Editor
Run Code
Ctrl Enter
Submit Code
Ctrl Shift Enter
Format Code
Shift Alt F
Toggle Comment
Ctrl /
Undo
Ctrl Z
Redo
Ctrl Y
Navigation
Global Search
/
Show Shortcuts
?
Close Modal
Esc

🔍 Interactive Debugger

0 / 0

Analyzing your code...

📦 Variables

No variables yet

📚 Call Stack
main() line 1
📤 Output
We use cookies

Essential cookies are always active. You can choose to enable preference and analytics cookies. Learn more