Data Structures: Cycles in a Linked List

HackerRank · Beginner ·⚡ Algorithms & Data Structures ·9y ago
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 HackerRank for Professors
HackerRank for Professors
HackerRank
2 Why CareerCup's Gayle Laakmann McDowell Loves HackerRank [Testimonial]
Why CareerCup's Gayle Laakmann McDowell Loves HackerRank [Testimonial]
HackerRank
3 How to Leverage Data-Driven Insights to Improve Recruiting Results
How to Leverage Data-Driven Insights to Improve Recruiting Results
HackerRank
4 Hire Top Linux Talent and System Admins with SudoRank [Webinar]
Hire Top Linux Talent and System Admins with SudoRank [Webinar]
HackerRank
5 How Zenefits Hired 10 Engineers in 10 Days with HackerRank's CodeSprint
How Zenefits Hired 10 Engineers in 10 Days with HackerRank's CodeSprint
HackerRank
6 Hire the hottest SQL talent with DbRank from HackerRank [Tutorial]
Hire the hottest SQL talent with DbRank from HackerRank [Tutorial]
HackerRank
7 How to Use HackerRank's CodePair Tool [Tutorial]
How to Use HackerRank's CodePair Tool [Tutorial]
HackerRank
8 Find Linux Talent with SudoRank challenges [Tutorial]
Find Linux Talent with SudoRank challenges [Tutorial]
HackerRank
9 VMware's Mat Connot details his favorite new way to engage top programmers
VMware's Mat Connot details his favorite new way to engage top programmers
HackerRank
10 An Inside Look at Coinbase's Recruiting Strategy [webinar]
An Inside Look at Coinbase's Recruiting Strategy [webinar]
HackerRank
11 How Evernote Enhanced Their Tech Recruiting Process
How Evernote Enhanced Their Tech Recruiting Process
HackerRank
12 5 strategies for being a tech recruiting champion with HackerRank [Webinar]
5 strategies for being a tech recruiting champion with HackerRank [Webinar]
HackerRank
13 HackerRank Story - Lets make the world flat!
HackerRank Story - Lets make the world flat!
HackerRank
14 Data Structures: Hash Tables
Data Structures: Hash Tables
HackerRank
15 Data Structures: Anagram Problem Solution
Data Structures: Anagram Problem Solution
HackerRank
16 Algorithms: Solve 'Lonley Integer' Using Bit Manipulation
Algorithms: Solve 'Lonley Integer' Using Bit Manipulation
HackerRank
17 Big O Notation
Big O Notation
HackerRank
18 Algorithms: Graph Search, DFS and BFS
Algorithms: Graph Search, DFS and BFS
HackerRank
19 Algorithms: Bit Manipulation
Algorithms: Bit Manipulation
HackerRank
20 Data Structures: Solve 'Find the Running Median' Using Heaps
Data Structures: Solve 'Find the Running Median' Using Heaps
HackerRank
21 Data Structures: Heaps
Data Structures: Heaps
HackerRank
22 Algorithms: Memoization and Dynamic Programming
Algorithms: Memoization and Dynamic Programming
HackerRank
23 Algorithms: Sort An Array with Comparator
Algorithms: Sort An Array with Comparator
HackerRank
24 Algorithms: Solve 'Coin Change' Using Memoization and DP
Algorithms: Solve 'Coin Change' Using Memoization and DP
HackerRank
25 Data Structures: Solve 'Contacts' Using Tries
Data Structures: Solve 'Contacts' Using Tries
HackerRank
26 Data Structures: Tries
Data Structures: Tries
HackerRank
27 Algorithms: Bubble Sort
Algorithms: Bubble Sort
HackerRank
28 Algorithms: Merge Sort
Algorithms: Merge Sort
HackerRank
29 Algorithms: Quicksort
Algorithms: Quicksort
HackerRank
30 Data Structures: Binary Search Tree
Data Structures: Binary Search Tree
HackerRank
31 Data Structures: Trees
Data Structures: Trees
HackerRank
32 Algorithms: Solve 'Shortest Reach' Using BFS
Algorithms: Solve 'Shortest Reach' Using BFS
HackerRank
33 Algorithms: Solve 'Connected Cells' Using DFS
Algorithms: Solve 'Connected Cells' Using DFS
HackerRank
34 Algorithms: Solve 'Recursive Staircase' Using Recursion
Algorithms: Solve 'Recursive Staircase' Using Recursion
HackerRank
35 Algorithms: Binary Search
Algorithms: Binary Search
HackerRank
36 Algorithms: Solve 'Ice Cream Parlor' Using Binary Search
Algorithms: Solve 'Ice Cream Parlor' Using Binary Search
HackerRank
37 Data Structures: Linked Lists
Data Structures: Linked Lists
HackerRank
Data Structures: Cycles in a Linked List
Data Structures: Cycles in a Linked List
HackerRank
39 Data Structures: Stacks and Queues
Data Structures: Stacks and Queues
HackerRank
40 Data Structures: Queue With Two Stacks
Data Structures: Queue With Two Stacks
HackerRank
41 Data Structures: Balanced Parentheses in Expression
Data Structures: Balanced Parentheses in Expression
HackerRank
42 Algorithms: Recursion
Algorithms: Recursion
HackerRank
43 How to Hire for Your Startup [Collision Panel Video]
How to Hire for Your Startup [Collision Panel Video]
HackerRank
44 HackerRank main() San Francisco | November 8, 2018
HackerRank main() San Francisco | November 8, 2018
HackerRank
45 The Enterprise Playbook for Technical Hiring
The Enterprise Playbook for Technical Hiring
HackerRank
46 Remote Hiring Colloquy with EY's Dipika Kapadia & BigBasket's Rupesh Kumar
Remote Hiring Colloquy with EY's Dipika Kapadia & BigBasket's Rupesh Kumar
HackerRank
47 Remote Hiring Colloquy with Hackerrank's Hari K, Akamai's Neha Akhouri & Infosys's Rafee Tarafdar
Remote Hiring Colloquy with Hackerrank's Hari K, Akamai's Neha Akhouri & Infosys's Rafee Tarafdar
HackerRank
48 Building a Culture for Developer Innovation
Building a Culture for Developer Innovation
HackerRank
49 Developer Trends in 2020 and Beyond
Developer Trends in 2020 and Beyond
HackerRank
50 HackerRank's Livestream: Accelerating Developer Innovation at PhonePe
HackerRank's Livestream: Accelerating Developer Innovation at PhonePe
HackerRank
51 Aadil Bandukwala converses with Rahul Chari about HackerRank's upcoming livestream
Aadil Bandukwala converses with Rahul Chari about HackerRank's upcoming livestream
HackerRank
52 Accelerating Developer Innovation at PhonePe with Rahul Chari
Accelerating Developer Innovation at PhonePe with Rahul Chari
HackerRank
53 The Future of Work for Developers
The Future of Work for Developers
HackerRank
54 Scaling AI from Proof of Concept to Production
Scaling AI from Proof of Concept to Production
HackerRank
55 The Secret Sauce to getting hired in Myntra’s Tech Team
The Secret Sauce to getting hired in Myntra’s Tech Team
HackerRank
56 Reimagining Money with Paypal
Reimagining Money with Paypal
HackerRank
57 Engineering Predictions for 2021 and Beyond! 🎬
Engineering Predictions for 2021 and Beyond! 🎬
HackerRank
58 Future-forward Tech & Careers with BNY Mellon
Future-forward Tech & Careers with BNY Mellon
HackerRank
59 How Atlassian Approaches Diversity and Inclusion with Balance & Belonging
How Atlassian Approaches Diversity and Inclusion with Balance & Belonging
HackerRank
60 Connecting Global Tech Ecosystems: Andela Shines a Light on Africa’s Developer Talent
Connecting Global Tech Ecosystems: Andela Shines a Light on Africa’s Developer Talent
HackerRank

Learn how to detect cycles in linked lists using two pointers moving at different speeds. This technique is useful for solving common interview questions and can be applied to other data structures.

Key Takeaways
  1. Initialize two pointers, fast and slow, to the head of the linked list
  2. Move fast two nodes at a time and slow one node at a time
  3. Check if fast and slow collide, indicating a cycle
  4. If no collision, check if fast or slow reaches the end of the list
  5. Return true if a cycle is detected, false otherwise
💡 Using two pointers moving at different speeds can efficiently detect cycles in linked lists

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →