Skip to content

Commit 77a8eeb

Browse files
committed
Implement linked-list-cycle-ii
https://leetcode.com/problems/linked-list-cycle-ii time: 4ms time-rank: 98.90% time-complexity: O(N) space: 7.8MB space-rank: 89.71% space-complexity: O(1) This solution adds no extra space but destroys the input. While the cost of checking if a node is visited is still O(1), this solution is faster than an unordered_set<LinkedList*> lookup because no hashing is performed, values are likely still in cache, and it is simply a const comparison. Fixes #228 Signed-off-by: Christopher Friedt <[email protected]>
1 parent f6c56f7 commit 77a8eeb

File tree

1 file changed

+5
-19
lines changed

1 file changed

+5
-19
lines changed

linked-list-cycle-ii.cpp

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,37 +22,23 @@
2222
* SOFTWARE.
2323
*/
2424

25-
#include <unordered_set>
26-
2725
using namespace std;
2826

2927
// https://leetcode.com/problems/linked-list-cycle-ii
3028

29+
#define CYCLE 0xc7c1e
30+
3131
class Solution {
3232
public:
33+
// this solution is destructive of the input, but it's O(1) space complexity
3334
ListNode *detectCycle(ListNode *head) {
34-
unordered_set<ListNode *> visited;
3535
ListNode *it;
3636
for (it = head; it != NULL; it = it->next) {
37-
if (visited.end() != visited.find(it)) {
37+
if (it->val == CYCLE) {
3838
return it;
3939
}
40-
visited.insert(it);
40+
it->val = CYCLE;
4141
}
4242
return it;
4343
}
44-
45-
/*
46-
// Recursive solution (obviously better to use iterative)
47-
ListNode *helper(unordered_set<ListNode *> &visited, ListNode *n) {
48-
if (NULL == n) {
49-
return NULL;
50-
}
51-
if (visited.end() != visited.find(n)) {
52-
return n;
53-
}
54-
visited.insert(n);
55-
return helper(visited, n->next);
56-
}
57-
*/
5844
};

0 commit comments

Comments
 (0)