Merge Two Ordered Sequences
GoogleOnsiteMedium
You are given two integer arrays a and b. Within each array the order is a rule: an element must come before every element that appears after it in the same array. A value that appears in both arrays is the same item. Implement can_merge(a, b) to decide whether all distinct values can be laid out in one sequence, each value once, that keeps the order of a and the order of b.
Part 1: Merge Two Ordered Sequences
You are given two integer arrays a and b. Within each array, an element must come before every element after it, so a = [1, 3, 5] means 1 before 3 before 5. A value that appears in both arrays is the same item.
Return true if the distinct values of a and b can be laid out in a single sequence, each value once, that keeps the order of a and the order of b. Return false otherwise.
- Example 1
- a
[1,2,3]- b
[2,4,5]- Output
true
Why: The order 1, 2, 3, 4, 5 keeps 1, 2, 3 in order and 2, 4, 5 in order.
- Example 2
- a
[1,6,4]- b
[4,1]- Output
false
Why:
aneeds 1 before 4 andbneeds 4 before 1, so no single order works.
Constraints
- 0 <= len(
a) <= 10^5 - 0 <= len(
b) <= 10^5 - The values within
aare distinct - The values within
bare distinct - -10^9 <=
a[i]<= 10^9 - -10^9 <=
b[i]<= 10^9