Introduction
The Fast & Slow pointer approach, also known as the Hare & Tortoise algorithm, is a pointer algorithm that uses two pointers which move through the array (or sequence/LinkedList) at different speeds. This approach is quite useful when dealing with cyclic LinkedLists or arrays.
By moving at different speeds (say, in a cyclic LinkedList), the algorithm proves that the two pointers are bound to meet. The fast pointer should catch the slow pointer once both the pointers are in a cyclic loop.
One of the famous problems solved using this technique was Finding a cycle in a LinkedList. Let’s jump onto this problem to understand the Fast & Slow pattern.
LinkedList Cycle (easy)
Top Interview 150 | 141. Linked List Cycle Design Gurus Educative.io
Problem Statement
Given the head of a Singly LinkedList, write a function to determine if the LinkedList has a cycle in it or not.
Constraints:
- The number of the nodes in the list is in the range [0, 10^4].
- 1 <= Node.val <= 10^5
Solution
Imagine two racers running in a circular racing track. If one racer is faster than the other, the faster racer is bound to catch up and cross the slower racer from behind. We can use this fact to devise an algorithm to determine if a LinkedList has a cycle in it or not.
Imagine we have a slow and a fast pointer to traverse the LinkedList. In each iteration, the slow pointer moves one step and the fast pointer moves two steps. This gives us two conclusions:
- If the LinkedList doesn’t have a cycle in it, the fast pointer will reach the end of the LinkedList before the slow pointer to reveal that there is no cycle in the LinkedList.
- The slow pointer will never be able to catch up to the fast pointer if there is no cycle in the LinkedList.
If the LinkedList has a cycle, the fast pointer enters the cycle first, followed by the slow pointer. After this, both pointers will keep moving in the cycle infinitely. If at any stage both of these pointers meet, we can conclude that the LinkedList has a cycle in it. Let’s analyze if it is possible for the two pointers to meet. When the fast pointer is approaching the slow pointer from behind we have two possibilities:
- The fast pointer is one step behind the slow pointer.
- The fast pointer is two steps behind the slow pointer.
All other distances between the fast and slow pointers will reduce to one of these two possibilities. Let’s analyze these scenarios, considering the fast pointer always moves first:
- If the fast pointer is one step behind the slow pointer: The fast pointer moves two steps and the slow pointer moves one step, and they both meet.
- If the fast pointer is two steps behind the slow pointer: The fast pointer moves two steps and the slow pointer moves one step. After the moves, the fast pointer will be one step behind the slow pointer, which reduces this scenario to the first scenario. This means that the two pointers will meet in the next iteration.
This concludes that the two pointers will definitely meet if the LinkedList has a cycle. A similar analysis can be done where the slow pointer moves first. Here is a visual representation of the above discussion:
Code
Here is what our algorithm will look like
1 | #class Node: |
Time Complexity
As we have concluded above, once the slow pointer enters the cycle, the fast pointer will meet the slow pointer in the same loop. Therefore, the time complexity of our algorithm will be O(N) where ‘N’ is the total number of nodes in the LinkedList.
Space Complexity
The algorithm runs in constant space O(1).
Similar Problems
Problem 1: Given the head of a LinkedList with a cycle, find the length of the cycle.
Solution: We can use the above solution to find the cycle in the LinkedList. Once the fast and slow pointers meet, we can save the slow pointer and iterate the whole cycle with another pointer until we see the slow pointer again to find the length of the cycle.
Here is what our algorithm will look like:
1 | #class Node: |
Time and Space Complexity: The above algorithm runs in O(N) time complexity and O(1) space complexity.
Start of LinkedList Cycle (medium)
142. Linked List Cycle II Design Gurus Educative.io
Problem Statement
Given the head of a Singly LinkedList that contains a cycle, write a function to find the starting node of the cycle.
Solution
If we know the length of the LinkedList cycle, we can find the start of the cycle through the following steps:
- Take two pointers. Let’s call them
pointer1
andpointer2
. - Initialize both pointers to point to the start of the LinkedList.
- We can find the length of the LinkedList cycle using the approach discussed in LinkedList Cycle. Let’s assume that the length of the cycle is ‘K’ nodes.
- Move
pointer2
ahead by ‘K’ nodes. - Now, keep incrementing
pointer1
andpointer2
until they both meet. - As
pointer2
is ‘K’ nodes ahead ofpointer1
, which means,pointer2
must have completed one loop in the cycle when both pointers meet. Their meeting point will be the start of the cycle.
Let’s visually see this with the above-mentioned Example-1:
We can use the algorithm discussed in LinkedList Cycle to find the length of the cycle and then follow the above-mentioned steps to find the start of the cycle.
Code
Here is what our algorithm will look like:
1 | #class Node: |
Time Complexity
As we know, finding the cycle in a LinkedList with ‘N’ nodes and also finding the length of the cycle requires O(N). Also, as we saw in the above algorithm, we will need O(N) to find the start of the cycle. Therefore, the overall time complexity of our algorithm will be O(N).
Space Complexity
The algorithm runs in constant space O(1).
Happy Number (medium)
Top Interview 150 | 202. Happy Number Design Gurus Educative.io
Problem Statement
Any number will be called a happy number if, after repeatedly replacing it with a number equal to the sum of the square of all of its digits, leads us to number ‘1’. All other (not-happy) numbers will never reach ‘1’. Instead, they will be stuck in a cycle of numbers which does not include ‘1’.
Example 1:
1 | Input: 23 |
- 2^2 + 3 ^2 = 4 + 9 = 13
- 1^2 + 3^2 = 1 + 9 = 10
- 1^2 + 0^2 = 1 + 0 = 1
Example 2:
1 | Input: 12 |
- 1^2 + 2 ^2 = 1 + 4 = 5
- 5^2 = 25
- 2^2 + 5^2 = 4 + 25 = 29
- 2^2 + 9^2 = 4 + 81 = 85
- 8^2 + 5^2 = 64 + 25 = 89
- 8^2 + 9^2 = 64 + 81 = 145
- 1^2 + 4^2 + 5^2 = 1 + 16 + 25 = 42
- 4^2 + 2^2 = 16 + 4 = 20
- 2^2 + 0^2 = 4 + 0 = 4
- 4^2 = 16
- 1^2 + 6^2 = 1 + 36 = 37
- 3^2 + 7^2 = 9 + 49 = 58
- 5^2 + 8^2 = 25 + 64 = 89
Step ‘13’ leads us back to step ‘5’ as the number becomes equal to ‘89’, this means that we can never reach ‘1’, therefore, ‘12’ is not a happy number.
Constraints:
- 1 <= n <= 231 - 1
Solution
The process, defined above, to find out if a number is a happy number or not, always ends in a cycle. If the number is a happy number, the process will be stuck in a cycle on number ‘1,’ and if the number is not a happy number then the process will be stuck in a cycle with a set of numbers. As we saw in Example-2 while determining if ‘12’ is a happy number or not, our process will get stuck in a cycle with the following numbers: 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89
We saw in the LinkedList Cycle problem that we can use the Fast & Slow pointers method to find a cycle among a set of elements. As we have described above, each number will definitely have a cycle. Therefore, we will use the same fast & slow pointer strategy to find the cycle and once the cycle is found, we will see if the cycle is stuck on number ‘1’ to find out if the number is happy or not.
Here is the visual representation of this algorithm for Example-2:
Code
Here is what our algorithm will look like:
1 | class Solution: |
Time Complexity
The time complexity of the algorithm is difficult to determine. However we know the fact that all unhappy numbers eventually get stuck in the cycle: 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4
This sequence behavior tells us two things:
- If the number NN is less than or equal to 1000, then we reach the cycle or ‘1’ in at most 1001 steps.
- For N > 1000, suppose the number has ‘M’ digits and the next number is ‘N1’. From the above Wikipedia link, we know that the sum of the squares of the digits of ‘N’ is at most $9^2M$, or $81M$ (this will happen when all digits of ‘N’ are ‘9’).
This means:
- $N1 < 81M$
- As we know $M = log(N+1)$
- Therefore: $N1 < 81 * log(N+1) => N1 = O(logN)$
This concludes that the above algorithm will have a time complexity of O(logN).
Space Complexity
The algorithm runs in constant space O(1).
Middle of the LinkedList (easy)
876. Middle of the Linked List Design Gurus Educative.io
Problem Statement
Given the head of a Singly LinkedList, write a method to return the middle node of the LinkedList.
If the total number of nodes in the LinkedList is even, return the second middle node.
Example 1:
1 | Input: 1 -> 2 -> 3 -> 4 -> 5 -> null |
Example 2:
1 | Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null |
Example 3:
1 | Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> null |
Constraints:
- The number of nodes in the list is in the range
[1, 100]
. 1 <= Node.val <= 100
Solution
One brute force strategy could be to first count the number of nodes in the LinkedList and then find the middle node in the second iteration. Can we do this in one iteration?
We can use the Fast & Slow pointers method such that the fast pointer is always twice the nodes ahead of the slow pointer. This way, when the fast pointer reaches the end of the LinkedList, the slow pointer will be pointing at the middle node.
let’s visualize example 3 via the below diagram.
Code
Here is what our algorithm will look like:
1 | #class Node: |
Time complexity
The above algorithm will have a time complexity of O(N) where ‘N’ is the number of nodes in the LinkedList.
Space complexity
The algorithm runs in constant space O(1).
Problem Challenge 1
234. Palindrome Linked List Design Gurus Educative.io
Palindrome LinkedList (medium)
Given the head of a Singly LinkedList, write a method to check if the LinkedList is a palindrome or not.
Your algorithm should use constant space and the input LinkedList should be in the original form once the algorithm is finished. The algorithm should have O(N)O(N) time complexity where ‘N’ is the number of nodes in the LinkedList.
Example 1:
1 | Input: 2 -> 4 -> 6 -> 4 -> 2 -> null |
Example 2:
1 | Input: 2 -> 4 -> 6 -> 4 -> 2 -> 2 -> null |
Constraints:
- The number of nodes in the list is in the range
[1, 10<sup>5</sup>]
. 0 <= Node.val <= 9
Solution
As we know, a palindrome LinkedList will have nodes values that read the same backward or forward. This means that if we divide the LinkedList into two halves, the node values of the first half in the forward direction should be similar to the node values of the second half in the backward direction. As we have been given a Singly LinkedList, we can’t move in the backward direction. To handle this, we will perform the following steps:
- We can use the Fast & Slow pointers method similar to Middle of the LinkedList to find the middle node of the LinkedList.
- Once we have the middle of the LinkedList, we will reverse the second half.
- Then, we will compare the first half with the reversed second half to see if the LinkedList represents a palindrome.
- Finally, we will reverse the second half of the LinkedList again to revert and bring the LinkedList back to its original form.
Here is the visual representation of this algorithm for Example-2:
Code
Here is what our algorithm will look like:
1 |
|
Time complexity
The above algorithm will have a time complexity of O(N) where ‘N’ is the number of nodes in the LinkedList.
Space complexity
The algorithm runs in constant space O(1).
# Problem Challenge 2
143. Reorder List Design Gurus Educative.io
Rearrange a LinkedList (medium)
Given the head of a Singly LinkedList, write a method to modify the LinkedList such that the nodes from the second half of the LinkedList are inserted alternately to the nodes from the first half in reverse order. So if the LinkedList has nodes 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null, your method should return 1 -> 6 -> 2 -> 5 -> 3 -> 4 -> null.
Your algorithm should not use any extra space and the input LinkedList should be modified in-place.
Example 1:
1 | Input: 2 -> 4 -> 6 -> 8 -> 10 -> 12 -> null |
Example 2:
1 | Input: 2 -> 4 -> 6 -> 8 -> 10 -> null |
Constraints:
- The number of nodes in the list is in the range [1, 5 * 10^4].
1 <= Node.val <= 1000
Solution
This problem shares similarities with Palindrome LinkedList
. To rearrange the given LinkedList we will follow the following steps:
- We can use the Fast & Slow pointers method similar to
Middle of the LinkedList
to find the middle node of the LinkedList. - Once we have the middle of the LinkedList, we will reverse the second half of the LinkedList.
- Finally, we’ll iterate through the first half and the reversed second half to produce a LinkedList in the required order.
Here is the visual representation of this algorithm for Example-1:
Code
Here is what our algorithm will look like:
1 | #class Node: |
Time Complexity
The above algorithm will have a time complexity of O(N) where ‘N’ is the number of nodes in the LinkedList.
Space Complexity
The algorithm runs in constant space O(1).
#Problem Challenge 3
457. Circular Array Loop Design Gurus Educative.io
Cycle in a Circular Array (hard)
We are given an array containing positive and negative numbers. Suppose the array contains a number ‘M’ at a particular index. Now, if ‘M’ is positive we will move forward ‘M’ indices and if ‘M’ is negative move backwards ‘M’ indices. You should assume that the array is circular which means two things:
- If, while moving forward, we reach the end of the array, we will jump to the first element to continue the movement.
- If, while moving backward, we reach the beginning of the array, we will jump to the last element to continue the movement.
Write a method to determine if the array has a cycle. The cycle should have more than one element and should follow one direction which means the cycle should not contain both forward and backward movements.
Example 1:
1 | Input: [1, 2, -1, 2, 2] |
Example 2:
1 | Input: [2, 2, -1, 2] |
Example 3:
1 | Input: [2, 1, -1, -2] |
Constraints:
1 <= nums.length <= 5000
- `-1000 <= nums[i] <= 1000
nums[i] != 0
Solution
This problem involves finding a cycle in the array and, as we know, the Fast & Slow pointer method is an efficient way to do that. We can start from each index of the array to find the cycle. If a number does not have a cycle we will move forward to the next element. There are a couple of additional things we need to take care of:
- As mentioned in the problem, the cycle should have more than one element. This means that when we move a pointer forward, if the pointer points to the same element after the move, we have a one-element cycle. Therefore, we can finish our cycle search for the current element.
- The other requirement mentioned in the problem is that the cycle should not contain both forward and backward movements. We will handle this by remembering the direction of each element while searching for the cycle. If the number is positive, the direction will be forward and if the number is negative, the direction will be backward. So whenever we move a pointer forward, if there is a change in the direction, we will finish our cycle search right there for the current element.
Here is the visual representation of this algorithm for Example-1:
Code
Here is what our algorithm will look like:
1 | class Solution: |
Time Complexity
The above algorithm will have a time complexity of O(N^2) where ‘N’ is the number of elements in the array. This complexity is due to the fact that we are iterating all elements of the array and trying to find a cycle for each element.
Space Complexity
The algorithm runs in constant space O(1).
An Alternate Approach
In our algorithm, we don’t keep a record of all the numbers that have been evaluated for cycles. We know that all such numbers will not produce a cycle for any other instance as well. If we can remember all the numbers that have been visited, our algorithm will improve to O(N) as, then, each number will be evaluated for cycles only once. We can keep track of this by creating a separate array however the space complexity of our algorithm will increase to O(N).