Problem 277637 · easy · Level 02 Linear Data Structures

Alternate Two Lists

arrays · interleaving · iteration

Given two lists a and b, return a new list that alternates their elements: a[0], b[0], a[1], b[1], .... When one list runs out, the remaining elements of the other list are appended in order.

Examples

Input:  a = [1, 3, 5, 7], b = [2, 4]
Output: [1, 2, 3, 4, 5, 7]
Explanation: after pairing 1-2 and 3-4, b is exhausted, so 5 and 7 follow.

Input:  a = [], b = [9, 8]
Output: [9, 8]

Constraints

  • 0 <= len(a), len(b) <= 10**5
  • Return a new list.
  • Target: O(len(a) + len(b)) time.

Goals

  • Walk two lists in lockstep
  • Append the leftover tail of the longer list
  • Handle one or both lists being empty
Starting Python…