On this page
Interleave Lists
TIP101 Unit 3 Session 2 (Click for link to problem statements)
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- What are the inputs?
- Two lists,
lst1andlst2.
- Two lists,
- What should the function return?
- A new list that alternates elements from the two lists, starting with the first element of
lst1.
- A new list that alternates elements from the two lists, starting with the first element of
- What if the lists have different lengths?
- Once the shorter list runs out, the remaining elements of the longer list are added in their original order.
- What if one of the lists is empty?
- The result holds the elements of the other list in their original order.
HAPPY CASE
Input: lst1 = [1, 2, 3], lst2 = [4, 5, 6]
Output: [1, 4, 2, 5, 3, 6]
Explanation: At each index, the element from lst1 is added first, then the element from lst2.
EDGE CASE
Input: lst1 = [1, 2, 3, 4, 5], lst2 = [10, 20]
Output: [1, 10, 2, 20, 3, 4, 5]
Explanation: lst2 runs out after index 1, so 3, 4 and 5 from lst1 are added in order.
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Loop from 0 to the longer length, and if valid, add an element from each list at that index.
1) Create an empty list for results
2) Find the length of the longer list
3) For each index from 0 to the longer length:
a) If index is valid in lst1, add that element to results
b) If index is valid in lst2, add that element to results
4) Return the results list
⚠️ Common Mistakes
- You might be tempted to write two different versions of the same code, one for when lst1 > lst2, and one for the opposite. Try to think of a way to write one block of code that works in both cases!
I-mplement
def interleave_lists(lst1, lst2):
result = []
lst1_len = len(lst1)
lst2_len = len(lst2)
length_of_longest_list = max(lst1_len, lst2_len)
for i in range(length_of_longest_list):
if i < lst1_len:
result.append(lst1[i])
if i < lst2_len:
result.append(lst2[i])
return result