Backwards Sled

I have come to love the sled. In fact if there was only one exercise that I could do the rest of my life it would be the sled. I had a relationship with the sled before learning about Athletic Truth…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




LeetCode Solution

141. Linked List Cycle

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

Example 1:

Example 2:

Example 3:

Constraints:

Solution 1:(Brute-force)

The brute-force solution uses a HashSet. Assuming how a basic HashSet works according to the Collections framework. We traverse through the entire list starting from the head of the list and add every new node encountered in to the list . Incase we come into a node that has already been encountered in the list then we return false. On reaching the last node if all nodes of the list are unique true is returned.

Solution 2:(two pointer method)

The optimal method being the use of two pointers. Here we use 2 pointers both starting from the head of the list. The first pointer holds the present node in the list and the second pointer holds the position of the node that is 2 nodes away from the current node. This loop iterates till the end and if there is no cycle present then returns false, else returns true.

Note:

The time complexities of both the methods remain the same that is O(n). However, the space complexities of the two solutions vary the brute force solution will be O(n), the optimal solution returns a space complexity of O(1) which is the space consumed by the list itself.

Add a comment

Related posts:

Hospice Volunteer Program

I would like to share an article written by our Volunteer Coordinator here at Parentis Hospice. Mrs. Taylor Edwards Harper who holds a Masters Degree in Psychology and is currently a doctoral student…

Depression and Single Motherhood Made Me A Shitty Friend

Since I began writing daily at the end of April, I’ve crossed paths with more new people than I have in the past decade. Maybe even longer. There’s no easy way to say this, but depression began to…

Benefits of Computer Annual Maintenance Contract

With the advent of information technology, the scenarios of businesses are changing day by day. Once the industry entirely relies on physical infrastructure but now it is more about IT…