You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This does not really seem impressing right? But it is from a computational POV. We want from a potential $O(n^2)$ down to $O(n)$. Yeah, that's gonna impress this bored interviewing senior 10x engineer. Too bad it's an Easy problem.
285
+
286
+
---
287
+
288
+
#### 2. Add Two Numbers (Medium)
289
+
290
+
We are asked to traverse two linked lists (they can have different lengths!), add the numbers, and return them in a linked list again. We know that due to the linked list nature, the numbers are placed there in reversed order.
291
+
292
+
##### So what is a linked list?
293
+
294
+
I wont really go into the details here, because it's not really necessary. It's basically a matryoshka.
295
+
296
+
```python
297
+
classListNode(object):
298
+
def__init__(self, val=0, next=None):
299
+
self.val = val
300
+
self.next =next
301
+
```
302
+
303
+
The class definition is pretty self-explanatory. You have a box with two holes. You put the value in one, and another box in the other hole.
304
+
305
+
##### Naive solution
306
+
307
+
First solution that comes to mind is to just traverse both lists, add encountered values (scaling them by $10^i$, where $i$ is value's position in list), iterate over the accumulated value's digits (either as a string or calculating single digits), and put it in a new linked list.
308
+
309
+
```python
310
+
defaddTwoNumbers(self, l1, l2):
311
+
acc =0
312
+
i =0
313
+
314
+
while l1 isnotNoneor l2 isnotNone:
315
+
v1 = l1.val if l1 isnotNoneelse0
316
+
v2 = l2.val if l2 isnotNoneelse0
317
+
318
+
acc += (v1 *10** i) + (v2 *10** i)
319
+
i +=1
320
+
321
+
l1 = l1.next if l1 isnotNoneelseNone
322
+
l2 = l2.next if l2 isnotNoneelseNone
323
+
324
+
ccs =str(acc)
325
+
urr = ListNode(int(accs[0]), None)
326
+
327
+
for el in accs[1:]:
328
+
curr = ListNode(int(el), curr)
329
+
330
+
return curr
331
+
```
332
+
333
+
The only hop here is that we have to handle the None tails of the lists we're traversing. Even though this solution is quite nice — time complexity is $O(n)$ — there are still some upgrades to be made, ie.:
334
+
335
+
- addition digit by digit, not by building a whole number, as this could lead to an overflow for very long lists,
336
+
- not using the int -> string conversion, cause even though it does not change the big O complexity, it adds an iteration
0 commit comments