Legacy Archive (2019): Originally written in Chinese on doubixie.com and translated into English for this edition. All archive posts · Home

Alibaba Interview Recap (LeetCode 21)

Original Chinese title: 阿里面试总结(leetcode21)

20190804 Alibaba Interview Coding Problem Recap

  • Alibaba Database Engineer role, second technical interview, the final coding question:

    # Merge two sorted linked lists and
    # return it as a new list.The new list should be made
    # by splicing together the nodes of the first two lists.
    # Example:
    # Input: 1->2->4, 1->3->4
    # Output: 1->1->2->3->4->4
  • Doing this with a regular list is easy, but when the list appeared as a class, my mind went completely blank.

    # Definition for singly-linked list.
    class ListNode(object):
        def __init__(self, x):
        self.val = x
        self.next = None
    
    class Solution(object):
        def mergeTwoLists(self, l1, l2):
  • I didn’t look closely at how the class was defined—I only noticed the format of the sample input—and got stuck trying to figure out how to declare the test data using that class, so I didn’t solve it in time. Writing this down as a reminder.

  • Later I found out it’s LeetCode #21. After reading the solution, I realized my core idea was right, and the whole mistake came from not reading the class definition, which threw everything off.

Pseudocode (What Not to Do)

11.next = 11.val
if 11.next != None:
    if 11.val > 12.val:
    11.next = 12.val

Solution

  • Because each Node stores val and next, you can simply compare the two lists directly to decide which is the head and which is the tail—I overcomplicated the problem.

    if l1 == None:
        return l2
    if l2 == None:
        return l1
    
    if l1.val <= l2.val:
        head = l1 
        head.next = self.mergeTwoLists(l1.next, l2)
    else:
        head = l2
        head.next = self.mergeTwoLists(l1, l2.next)
    
    return head 

Built-in Library Solutions

# Solution 1
# using sorted()
# to combine two sorted lists
res = sorted(test_list1 + test_list2)

## Solution 2 heapq.merge
from heapq import merge
# to combine two sorted lists
res = list(merge(test_list1, test_list2))

# printing result
print("The combined sorted list is : " + str(res))

Overly Complicated Solution When I Forgot Whether sort Is Ascending or Descending

def two(list_a, list_b):
list_c = []
while len(list_a) > 0 and len(list_b) > 0:
    if list_a[0] < list_b[0]:
        list_c.append(list_a[0])
        del list_a[0]
    else:
        list_c.append(list_b[0])
        del list_b[0]
list_c.extend(list_a)
list_c.extend(list_b)
return list_c

ret = two([1, 2, 4], [1, 3, 4])
print(ret)

Summary

  • My coding fluency isn’t where it needs to be. Not reading the problem carefully—and missing the class definition—was the biggest issue.
  • Can’t let my mindset collapse; once I panic, my IQ drops to zero. Need to stay calm.