Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Better Solution w/ Time Complexity O(N), Space complexity O(1)

kfaham

Jul 29, 2025

class Solution: def loopExists(self, arr): # T O(N) | S O(1) p1 = self.getNext(arr, 0) p2 = self.getNext(arr, self.getNext(arr, 0)) # step 1) find an element within the cycle while p1 != p2: p1 = self.getNext(arr, p1) p2 = self.getNext(arr, self.getNext(arr, p2)) # step 2) make sure its a cycle that contains atleast 1 other element p2 = self.getNext(arr, p1) if p1 == p2: return False # step 3) make sure all the directions of the cycle are the same while p1 != p2: if (arr[p2] < 0 and arr[p1] > 0) or (arr[p2] > 0 and arr[p1] < 0): return False p2 = self.getNext(arr, p2) return True def getNext(self, arr, index): # T O(1) | S O(1) if index is None or len(arr) - 1 < index: return None nextIndex = index + arr[index] if nextIndex > len(arr) - 1: nextIndex -= len(arr) elif nextIndex < 0: nextIndex += len(arr) - 1 return nextIndex

0

0

Comments
Comments

On this page