iq.lab
Python starts when a code cell comes near or you run one
07 Linked lists

Checkpoint

Linked lists

These questions mix all three lessons: moving names and changing links, the dummy head, fast and slow pointers, and the LRU cache. Every input is new, so draw it on paper before you answer: one box per node, one arrow per next, and a tag for each name that points at a node. The last two ask for code: a list edit that joins the first two lessons, and a small class built the way the cache is built.

  1. Question 1 of 12.

    Some lines here move a name and some change a node. Type exactly what this prints. list_values(head) returns the values of the chain that starts at head.

    head = build_list([4, 1, 7])
    cur = head
    cur = cur.next
    cur.val = 9
    cur.next = None
    print(list_values(head))
    print(cur.val, head.val)
    
  2. Question 2 of 12.

    This is the reversal loop from the first lesson, stopped after 2 passes (for _ in range(2) repeats its body twice). Type exactly what it prints.

    head = build_list([1, 2, 3, 4, 5])
    prev = None
    cur = head
    for _ in range(2):
        nxt = cur.next
        cur.next = prev
        prev = cur
        cur = nxt
    print(list_values(prev))
    print(list_values(cur))
    print(list_values(head))
    
  3. Question 3 of 12.

    This is the merge from the first lesson with one line left out: the line after the loop that attaches the rest of the other list.

    def merge_two_lists(list1, list2):
        dummy = ListNode()
        tail = dummy
        while list1 is not None and list2 is not None:
            if list1.val <= list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next
            tail = tail.next
        return dummy.next

    How many values does list_values(merge_two_lists(build_list([1, 4]), build_list([2, 3, 7, 8]))) hold? Type a whole number.

    values

    Type a number: 12, -1, 0.5 and 3/4 all work.

  4. Question 4 of 12.

    This is the middle walk from the second lesson, run on two lists. Type exactly what it prints.

    def middle(head):
        slow = head
        fast = head
        while fast is not None and fast.next is not None:
            slow = slow.next
            fast = fast.next.next
        return slow
    
    print(middle(build_list([10, 20, 30, 40, 50, 60])).val)
    print(middle(build_list([10, 20, 30, 40, 50, 60, 70])).val)
    
  5. Question 5 of 12.

    In 5 → 1 → 8 → 3 → 6 → 9, the 9 points back to the 1, so the loop is 1, 8, 3, 6, 9. Run the two-speed cycle check by hand. Both walkers start on the 5; each pass moves slow one node and fast two, then checks slow is fast. After how many passes is slow is fast true? Type a whole number.

    passes

    Type a number: 12, -1, 0.5 and 3/4 all work.

  6. Question 6 of 12.

    This removal starts both walkers on head instead of on a dummy head:

    def remove_nth(head, n):
        fast = head
        slow = head
        for _ in range(n):
            fast = fast.next
        while fast.next is not None:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return head

    Which call raises an AttributeError?

  7. Question 7 of 12.

    This is the OrderedDict cache from the last lesson, with capacity 2. Type exactly what it prints.

    from collections import OrderedDict
    
    class LRUCache:
        def __init__(self, capacity):
            self.capacity = capacity
            self.data = OrderedDict()  # least recently used first
    
        def get(self, key):
            if key not in self.data:
                return -1
            self.data.move_to_end(key)
            return self.data[key]
    
        def put(self, key, value):
            if key in self.data:
                self.data.move_to_end(key)
            self.data[key] = value
            if len(self.data) > self.capacity:
                self.data.popitem(last=False)
    
    cache = LRUCache(2)
    cache.put(1, 10)
    cache.put(2, 20)
    print(cache.get(1))
    cache.put(3, 30)
    print(cache.get(2))
    cache.put(1, 15)
    cache.put(4, 40)
    print(cache.get(3), cache.get(1), cache.get(4))
    
  8. Question 8 of 12.

    A teammate proposes the LRU cache with the same dict from key to node and the same two sentinels, but a singly linked list: each node has next and no prev. The order is the same, least recently used right after head. Which step can no longer be done in O(1) time?

  9. Question 9 of 12.

    A cache without sentinels links its real nodes straight to each other. The oldest node's prev is None, and the newest node's next is None. It unlinks a node with the same two lines as the lesson:

    def unlink(node):
        node.prev.next = node.next
        node.next.prev = node.prev

    The cache holds three nodes, for keys 1, 2 and 3, from oldest to newest. Which calls raise an AttributeError? Choose every one.

    Choose every option that applies.

  10. Question 10 of 12.

    Extra space is the memory a method needs beyond the input list itself. Which of these use O(1) extra space for a list of n nodes? Choose every one.

    Choose every option that applies.

  11. Question 11 of 12.

    Run the tests before you submit. This question counts as correct if your latest run passes every check.

    Code itDelete the middle node

    Write delete_middle(head), which removes the middle node of a linked list with at least one node and returns the head of what is left. For a list of n nodes, the middle is at position n // 2, counting from 0: in [8, 3, 5, 2, 7] it is the 5, and in [6, 1, 9, 4] it is the 9, the second of the two middles. A one-node list becomes empty, so return None. Change links only: the nodes that stay must be the original nodes.

    Try one walk with slow and fast. To remove a node you must stand on the node before it, so think about where slow should start. (Counting the nodes first also passes the tests.)

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.
  12. Question 12 of 12.

    Run the tests before you submit. This question counts as correct if your latest run passes every check.

    Code itRecently opened files

    An editor shows the files you opened recently, newest first, each name once. Write the class RecentFiles:

    • RecentFiles() starts with no files.
    • open(name) records that name was opened now. Opening a name that is already in the list moves it to the front; a name never appears twice.
    • recent(k) returns the k most recently opened names, newest first, or all of them if fewer than k were opened.

    open must take O(1) time on average, however many names there are, and recent(k) O(k) time. After open("a"), open("b"), open("c") and open("a"), recent(2) is ["a", "c"].

    Build it the way the cache is built: a dict from name to node, plus a doubly linked list between two sentinels. An OrderedDict would also pass, but build the list by hand here, because that is what an interviewer may ask to see. The tests include 80,000 calls to open.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.
0 of 12 answered. Unanswered questions count as wrong.