Skip to content

Commit b4b3c5b

Browse files
committed
CTCI Chapter 2 Complete
Python Solutions
1 parent 777becd commit b4b3c5b

File tree

4 files changed

+64
-5
lines changed

4 files changed

+64
-5
lines changed

CTCI/Chapter2/2.6-Palindrome.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
# CTCI 2.5
2-
# Sum Lists
1+
# CTCI 2.6
2+
# Palindrome
33

44
import unittest
55
#from LinkedList import LinkedList

CTCI/Chapter2/2.7-Intersection.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
# CTCI 2.5
2-
# Sum Lists
1+
# CTCI 2.7
2+
# Intersection
33

44
import unittest
55
#from LinkedList import LinkedList

CTCI/Chapter2/2.8-Loop_Detection.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# CTCI 2.8
2+
# Loop Detection
3+
4+
import unittest
5+
#from LinkedList import LinkedList
6+
7+
# My Solution
8+
def detect_cycle(head):
9+
nodes = []
10+
curr = head
11+
while curr:
12+
if curr in nodes:
13+
return curr
14+
nodes.append(curr)
15+
curr = curr.next
16+
17+
return None
18+
19+
#-------------------------------------------------------------------------------
20+
# CTCI Solution
21+
def loop_detection(ll):
22+
fast = slow = ll.head
23+
24+
while fast and fast.next:
25+
fast = fast.next.next
26+
slow = slow.next
27+
if fast is slow:
28+
break
29+
30+
if fast is None or fast.next is None:
31+
return None
32+
33+
slow = ll.head
34+
while fast is not slow:
35+
fast = fast.next
36+
slow = slow.next
37+
38+
return fast
39+
40+
#-------------------------------------------------------------------------------
41+
#Testing
42+
43+
class Node():
44+
def __init__(self, data, next=None):
45+
self.data, self.next = data, next
46+
47+
class Test(unittest.TestCase):
48+
def test_detect_cycle(self):
49+
head1 = Node(100,Node(200,Node(300)))
50+
self.assertEqual(detect_cycle(head1), None)
51+
node1 = Node(600)
52+
node2 = Node(700,Node(800,Node(900,node1)))
53+
node1.next = node2
54+
head2 = Node(500,node1)
55+
self.assertEqual(detect_cycle(head2), node1)
56+
57+
if __name__ == "__main__":
58+
unittest.main()

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,8 @@ Cracking the Coding Interview 6th Edition Python Solutions
116116
| 2.4| | Partition | [Python](CTCI/Chapter2/2.4-Partition.py) |
117117
| 2.5| | Sum Lists | [Python](CTCI/Chapter2/2.5-Sum_Lists.py) |
118118
| 2.6| | Palindrome | [Python](CTCI/Chapter2/2.6-Palindrome.py) |
119-
| 2.7| | Intersection | [Python](CTCI/Chapter2/2.7-Intersection.py) |
119+
| 2.7| | Intersection | [Python](CTCI/Chapter2/2.7-Intersection.py) |
120+
| 2.8| | Loop Detection | [Python](CTCI/Chapter2/2.8-Loop_Detection.py) |
120121

121122
---
122123

0 commit comments

Comments
 (0)