Skip to content

Preserving unread state before mutation [ref]

Problem

  • Save the second node before disconnecting it from a linked list starting at 1.
  • Merge [1, 3, 0, 0] and [2, 4] from the back without overwriting unread values.
  • Update hold = -3, sold = 5, and rest = 2 from their old states.
  • Save and restore the sole character in board = [["A"]] around a temporary mark.
  • Swap the unclassified index 0 of [2, 0, 1] with index 2 without advancing index 0.

Python solution

class Node:
    def __init__(self, val, next=None):
        self.val, self.next = val, next

cur = Node(1, Node(2, Node(3)))
nxt = cur.next
cur.next = None
nxt.val  # 2

nums1, nums2 = [1, 3, 0, 0], [2, 4]
i, j, k = 1, 1, 3
while i >= 0 and j >= 0:
    if nums1[i] > nums2[j]:
        nums1[k] = nums1[i]
        i -= 1
    else:
        nums1[k] = nums2[j]
        j -= 1
    k -= 1
while j >= 0:
    nums1[k] = nums2[j]
    j -= 1
    k -= 1
nums1  # [1, 2, 3, 4]

hold, sold, rest = -3, 5, 2
old_hold, old_sold, old_rest = hold, sold, rest
hold = max(old_hold, old_rest - 4)
sold = old_hold + 4
rest = max(old_rest, old_sold)
(hold, sold, rest)  # (-2, 1, 5)

board = [["A"]]
old = board[0][0]
board[0][0] = "#"
board[0][0] = old
board  # [['A']]

nums = [2, 0, 1]
i, r = 0, 2
nums[i], nums[r] = nums[r], nums[i]
r -= 1
(i, r, nums)  # (0, 1, [1, 0, 2])