#K70277. Interleaving Two Lists
Interleaving Two Lists
Interleaving Two Lists
You are given two lists. Your task is to interleave the elements of these two lists: take one element from the first list, then one from the second list, and continue this alternation. If one list runs out of elements before the other, append the remaining elements from the longer list at the end.
Note: The input lists can contain elements of different data types (e.g., integers, strings, booleans). The interleaving should preserve the order of elements in each list.
For example, if the input lists are:
list1 = [1, 2, 3] list2 = ["a", "b", "c"]
Then the output should be:
[1, "a", 2, "b", 3, "c"]
If one list is longer, the extra elements are appended:
list1 = [1, 2] list2 = ["a", "b", "c", "d"] Output: [1, "a", 2, "b", "c", "d"]
Solve the problem by reading from stdin
and writing your result to stdout
. The input will be provided as two lines, each being a valid JSON array.
Mathematical formulation:
Let \(A = [a_0, a_1, \dots, a_{n-1}]\) and \(B = [b_0, b_1, \dots, b_{m-1}]\). Define \(k = \min(n, m)\). The resulting list \(R\) is defined as:
[ R = [a_0, b_0, a_1, b_1, \dots, a_{k-1}, b_{k-1}] \cup \begin{cases} [a_k, a_{k+1}, \dots, a_{n-1}], & \text{if } n > m,\ [b_k, b_{k+1}, \dots, b_{m-1}], & \text{if } m > n. \end{cases} ]
Output \(R\) as a JSON array.
inputFormat
The input consists of two lines. Each line contains a JSON array representing a list. The first line corresponds to list1
and the second line corresponds to list2
.
Example:
[1, 2, 3] ["a", "b", "c"]
outputFormat
The output should be a JSON array printed on a single line which represents the interleaved list.
Example output for the above input:
[1, "a", 2, "b", 3, "c"]## sample
[1, 2, 3]
["a", "b", "c"]
[1, "a", 2, "b", 3, "c"]