Add Two Numbers - Leetcode 2 (Python)

preview_player
Показать описание
How to solve leetcode #2 - Add Two Numbers in Python. This is one of the most popular leetcode questions and is asked by a lot of big tech companies such as Amazon, Facebook, Google, and Microsoft. This video assumes prior knowledge of Linked Lists. This is a great question to prep for technical interviews.

0:00 - Intro
0:52 - conceptual solution
4:33 - code

#fang #leetcode #codinginterview #linkedlists #python
Рекомендации по теме
Комментарии
Автор

Thanks for watching!

Time Complexity: O(max(m, n)) since we iterate through both lists only once.
Space O(max(m, n)) because the new list will be max size max(m, n) + 1.

class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
carry, dummy = 0, ListNode()
cur = dummy

while l1 or l2:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0

result = v1 + v2 + carry
cur.next = ListNode(result % 10)
cur = cur.next
carry = result // 10

l1 = l1.next if l1 else None
l2 = l2.next if l2 else None

if carry != 0:
cur.next = ListNode(carry)

return dummy.next

leetprep
Автор

Great explanation! As a self-taught, who is now preparing for interviews with Leet I really, really appreciate your videos! Keep going!

maddiek
join shbcf.ru