Skip to content

Commit 02394e5

Browse files
committed
2. partially complete, optimal solution waiting
1 parent 246c0ad commit 02394e5

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

README.md

+56
Original file line numberDiff line numberDiff line change
@@ -282,3 +282,59 @@ def containsDuplicate(self, nums):
282282
```
283283

284284
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+
class ListNode(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+
def addTwoNumbers(self, l1, l2):
311+
acc = 0
312+
i = 0
313+
314+
while l1 is not None or l2 is not None:
315+
v1 = l1.val if l1 is not None else 0
316+
v2 = l2.val if l2 is not None else 0
317+
318+
acc += (v1 * 10 ** i) + (v2 * 10 ** i)
319+
i += 1
320+
321+
l1 = l1.next if l1 is not None else None
322+
l2 = l2.next if l2 is not None else None
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
337+
338+
##### Optimal solution
339+
340+

0 commit comments

Comments
 (0)