LeetCode #141 — You are given an interface for a linked list, LLI, with a single method, next, which returns the next element. Write a function that returns True if the list contains a cycle and False if it does not.
Asked at
AI answer
I’ll use Floyd’s algorithm: one pointer moves one step at a time, while the other moves two steps. If the pointers meet, there is a cycle; if the fast pointer reaches the end (None), there is no cycle. Time complexity is O(n), and extra space complexity is O(1).
def has_cycle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
You need to compare the nodes themselves, not their values: different nodes can contain identical data.
Also asked at Valletta Software Development
- What is the reason for your desire to change jobs?
- Which direction would you like to develop in? Would you like to move into leadership or management, or stay in a hands-on role?
- At [компания], I'm interested in tasks that helped you grow as an engineer and developer—something challenging and out of the ordinary, the kind of thing that still makes you wake up in a cold sweat and then breathe a sigh of relief that it's behind you. Did you have anything like that? What was the task, and what made it difficult?
- Which metrics do you choose for binary classification, regression, and ranking tasks?
- Have you ever set up CI/CD pipelines and production monitoring yourself?
Similar questions
- How would you make this code faster? What data structure could you use to improve its performance?
- Given a list of length n consisting of zeros and ones, find the maximum number of consecutive ones. For example, [0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1] → 3.
- Write a function that finds the top k most frequently occurring characters in a string of length n.
- Write a decorator that caches the results of a function.
- What is a circular reference?