Google questions

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.

  1. 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.

  2. Example 2
    a
    [1,6,4]
    b
    [4,1]
    Output
    false

    Why: a needs 1 before 4 and b needs 4 before 1, so no single order works.

Constraints

  • 0 <= len(a) <= 10^5
  • 0 <= len(b) <= 10^5
  • The values within a are distinct
  • The values within b are distinct
  • -10^9 <= a[i] <= 10^9
  • -10^9 <= b[i] <= 10^9
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Merge Two Ordered Sequences: Google interview question | LoopCoach