Data Structures: Cycles in a Linked List
Skills:
Algorithm Basics80%
Learn how to solve the most common interview question for Linked Lists. This video is a part of HackerRank's Cracking The Coding Interview Tutorial with Gayle Laakmann McDowell. http://www.hackerrank.com/domains/tutorials/cracking-the-coding-interview?utm_source=video&utm_medium=youtube&utm_campaign=ctci
What You'll Learn
The video teaches how to detect a cycle in a linked list using two pointers moving at different speeds, a common interview question for linked lists. The technique is implemented in a method called hasCycle that takes a head node and returns a Boolean indicating whether a cycle is present.
Full Transcript
hi I'm Gail lock McDow author of cracking the coding interview today we're going to cover a classic interview question given a link list how would you detect a cycle in the list this is a classic link list question possibly the most common interview question for link lists and also demonstrates a really common technique so the question is as follows you have a link list and you want to figure out if it contains a cycle a cycle means that the link list actually Loops back on itself not necessarily to the beginning of the link list but somewhere in the link list so one way of solving it is that you walk through the link list and if you and you mark each node and if you've seen if you get to know that you've seen before then you know that it contains a cycle that's a great technique if you can modify the link list but if you can't that won't really work so here's another way of thinking about it imagine the link list was like a racetrack and you driving around it well one way you know that you have a a link a loop in the in the list is if you've seen somewhere that you've been before again that's kind of the first technique another way is imagine there are two cars driving around this racetrack if the cars drive at different speeds then you know that they will if there's a loop they they will eventually Collide they will eventually pass each other and we can do this exact technique on a link list so we can have two pointers moving through the link list at different speeds one Moving Two nodes for every time time the other pointer moves one note they will eventually Collide if there's a loop if there is no Loop then one will one or well both of them eventually will get to the end of the link list so let's try out this technique so we're going to call this method has cycle and it's going to take in a head node and then it's going to return a Boolean if it does in fact contain a cycle so first of all let's cover our null pointer check so if head is null then certainly there's no cycle other wise what we want to do is have two pointers one I'll call fast fast moves twice as fast as slow one and I'll start as a first approach having them both point to the head of the link list now we want to move through the link list so a fast does not equal null and slow does not equal null then if they've collided if fast and slow are at the same node then we know we found a cycle otherwise oops move each of these now fast is going to want to move two jumps for each time slow moves once so fast is going to move two so move fast to fast. next. next and slow is just going to move by one and if they get to the end then we return if we get get to the end and we haven't found a link a loop then they return false so before we run this let's think and make sure this code really makes sense so let's walk through it well first fast and slow are going to point to head and then we're going to get in here and say if fast is slow well that'll be a mistake because they're both already starting off the head so the very beginning L 16 will return true so actually what we want to do is start them off at slightly different points so fast is actually going to start off at the second node and slow is going to start off at the first and then let's make sure we don't have null pointer checks null pointer exceptions possible so let's look at all the points we have pointer so we have fast. next fast equals head. next head won't be null so that'll be okay then here what about this one what we're calling fast. next. nextt fast won't be null but fast. nextt might be null so let's throw that in as a case so we actually want to stop if fast. next does not equal no okay now I think our code looks pretty good fast will not be null fast. next will not be null so fast. next and X will be fine slow will will equal uh will not equal null so that'll be okay now it's possible that slow that this exception that this if statement is unnecessary you know it won't really cause a problem so I'll leave that in so now let's try running our code okay so I'm going to click this run code button and see what what happens perfect we passed the the test case so now I'm going to go ahead and submit our code great our code works so to walk through it again we set fast and slow fast to the second node and slow to the very first node then we walk through it as long as fast fast. next and and slow is not null then if they've collided then we know there's a loop otherwise move fast by one and then slow by one sorry fast by two and then slow by one if they get to the end and they haven't collided then we know that we can just return false there is no Loop now that you've seen this technique think about applying this in the future on other link list questions
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from HackerRank · HackerRank · 38 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
▶
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
HackerRank for Professors
HackerRank
Why CareerCup's Gayle Laakmann McDowell Loves HackerRank [Testimonial]
HackerRank
How to Leverage Data-Driven Insights to Improve Recruiting Results
HackerRank
Hire Top Linux Talent and System Admins with SudoRank [Webinar]
HackerRank
How Zenefits Hired 10 Engineers in 10 Days with HackerRank's CodeSprint
HackerRank
Hire the hottest SQL talent with DbRank from HackerRank [Tutorial]
HackerRank
How to Use HackerRank's CodePair Tool [Tutorial]
HackerRank
Find Linux Talent with SudoRank challenges [Tutorial]
HackerRank
VMware's Mat Connot details his favorite new way to engage top programmers
HackerRank
An Inside Look at Coinbase's Recruiting Strategy [webinar]
HackerRank
How Evernote Enhanced Their Tech Recruiting Process
HackerRank
5 strategies for being a tech recruiting champion with HackerRank [Webinar]
HackerRank
HackerRank Story - Lets make the world flat!
HackerRank
Data Structures: Hash Tables
HackerRank
Data Structures: Anagram Problem Solution
HackerRank
Algorithms: Solve 'Lonley Integer' Using Bit Manipulation
HackerRank
Big O Notation
HackerRank
Algorithms: Graph Search, DFS and BFS
HackerRank
Algorithms: Bit Manipulation
HackerRank
Data Structures: Solve 'Find the Running Median' Using Heaps
HackerRank
Data Structures: Heaps
HackerRank
Algorithms: Memoization and Dynamic Programming
HackerRank
Algorithms: Sort An Array with Comparator
HackerRank
Algorithms: Solve 'Coin Change' Using Memoization and DP
HackerRank
Data Structures: Solve 'Contacts' Using Tries
HackerRank
Data Structures: Tries
HackerRank
Algorithms: Bubble Sort
HackerRank
Algorithms: Merge Sort
HackerRank
Algorithms: Quicksort
HackerRank
Data Structures: Binary Search Tree
HackerRank
Data Structures: Trees
HackerRank
Algorithms: Solve 'Shortest Reach' Using BFS
HackerRank
Algorithms: Solve 'Connected Cells' Using DFS
HackerRank
Algorithms: Solve 'Recursive Staircase' Using Recursion
HackerRank
Algorithms: Binary Search
HackerRank
Algorithms: Solve 'Ice Cream Parlor' Using Binary Search
HackerRank
Data Structures: Linked Lists
HackerRank
Data Structures: Cycles in a Linked List
HackerRank
Data Structures: Stacks and Queues
HackerRank
Data Structures: Queue With Two Stacks
HackerRank
Data Structures: Balanced Parentheses in Expression
HackerRank
Algorithms: Recursion
HackerRank
How to Hire for Your Startup [Collision Panel Video]
HackerRank
HackerRank main() San Francisco | November 8, 2018
HackerRank
The Enterprise Playbook for Technical Hiring
HackerRank
Remote Hiring Colloquy with EY's Dipika Kapadia & BigBasket's Rupesh Kumar
HackerRank
Remote Hiring Colloquy with Hackerrank's Hari K, Akamai's Neha Akhouri & Infosys's Rafee Tarafdar
HackerRank
Building a Culture for Developer Innovation
HackerRank
Developer Trends in 2020 and Beyond
HackerRank
HackerRank's Livestream: Accelerating Developer Innovation at PhonePe
HackerRank
Aadil Bandukwala converses with Rahul Chari about HackerRank's upcoming livestream
HackerRank
Accelerating Developer Innovation at PhonePe with Rahul Chari
HackerRank
The Future of Work for Developers
HackerRank
Scaling AI from Proof of Concept to Production
HackerRank
The Secret Sauce to getting hired in Myntra’s Tech Team
HackerRank
Reimagining Money with Paypal
HackerRank
Engineering Predictions for 2021 and Beyond! 🎬
HackerRank
Future-forward Tech & Careers with BNY Mellon
HackerRank
How Atlassian Approaches Diversity and Inclusion with Balance & Belonging
HackerRank
Connecting Global Tech Ecosystems: Andela Shines a Light on Africa’s Developer Talent
HackerRank
More on: Algorithm Basics
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Bloom Filters, Explained Properly
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Medium · Python
🎓
Tutor Explanation
DeepCamp AI