less than 1 minute read

1721. Swapping Nodes in a Linked List (medium)

class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        arr = []
        temp = head
        while temp:
            arr.append(temp)
            temp = temp.next

        n = len(arr)
        a, b = arr[k - 1].val, arr[n - k].val
        # print(a, b)
        arr[k - 1].val = b
        arr[n - k].val = a

        return head

2462. Total Cost to Hire K Workers (medium)

class Solution:
    def totalCost(self, costs: List[int], k: int, size: int) -> int:
        ans = 0
        n = len(costs)
        q = []
        qq = []
        l, r = 0, n - 1

        for _ in range(k):
            while len(q) < size and l <= r: heappush(q, costs[l]); l+=1
            while len(qq) < size and l <= r: heappush(qq, costs[r]); r-=1

            a = q[0] if q else maxsize
            b = qq[0] if qq else maxsize

            if a <= b: ans += a; heappop(q)
            else: ans += b; heappop(qq)
        return ans