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, andrest = 2from their old states. - Save and restore the sole character in
board = [["A"]]around a temporary mark. - Swap the unclassified index
0of[2, 0, 1]with index2without advancing index0.
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])
Links¶
- 206. Reverse Linked List (Top Easy)
- 88. Merge Sorted Array (Top Easy)
- 75. Sort Colors (Top Medium)
- 309. Best Time to Buy and Sell Stock with Cooldown (Top Hard)
- 221. Maximal Square (Dynamic Programming)
- 1143. Longest Common Subsequence (Dynamic Programming)