Dual Pointer Assessment: Loop Detection and Ordered Pair Sum
Linked ListsAuto-graded · 21 test casesLast updated
Evaluate two algorithmic challenges using the two-pointer technique: detecting cyclic pointer references and locating index pairs for a target sum in an ordered list.
Write a function that solves two foundational foundational pointer-based algorithmic tasks in a single call.
Task 1: Simulated Cycle Detection
Determine whether a simulated singly linked list contains a cycle.
- The list elements are provided in the array
values. - Node
inormally points to nodei + 1for0 <= i < len(values) - 1. - The tail node (
len(values) - 1) points back to indexcycle_pos. Ifcycle_pos == -1, the tail points tonull(end of list, no cycle). - An empty array
valueshas no nodes and thus no cycle.
Return True if a traversal starting at index 0 eventually repeats a node, and False otherwise.
Task 2: Two Sum in an Ordered Array
Given a 1-indexed sorted list of integers numbers ordered in non-decreasing fashion, find two distinct indices whose elements sum to target.
- Return the 1-based indices as a 2-element list
[index1, index2]withindex1 < index2. - You may assume that
numberscontains exactly one valid pair that satisfies the requirement. - The same element index cannot be used twice.
Output Format
Return a dictionary containing two keys:
"has_cycle": a boolean indicating whether the simulated list has a cycle."two_sum": a list of two 1-based indices[index1, index2]meeting the target sum.
Constraints
0 <= len(values) <= 10^4-1 <= cycle_pos < len(values)2 <= len(numbers) <= 3 * 10^4-1000 <= numbers[i] <= 1000numbersis sorted in non-decreasing order.-2000 <= target <= 2000
Examples
Example 1
Input: solve_two_tasks([3, 2, 0, -4], 1, [2, 7, 11, 15], 9)
Output: {'has_cycle': True, 'two_sum': [1, 2]}
Example 2
Input: solve_two_tasks([1, 2], -1, [-3, -1, 0, 4], -4)
Output: {'has_cycle': False, 'two_sum': [1, 2]}
Example 3
Input: solve_two_tasks([1], 0, [2, 2], 4)
Output: {'has_cycle': True, 'two_sum': [1, 2]}
Hints
Hint 1
For loop detection, simulate Floyd's Tortoise and Hare approach: move one pointer by one step and another by two steps each iteration.
Hint 2
For finding the pair sum, initialize two pointers at opposite ends of the sorted array and move inward based on whether their sum is less than or greater than the target.
Hint 3
Make sure to return 1-based indices for the array pair matching task.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem addresses two classic algorithmic tasks using the two-pointer pattern.
Part 1: Cycle Detection (Floyd's Tortoise and Hare)
To detect cycles in linear data structures without auxiliary memory:
- Maintain two pointers: a
slowpointer moving one node at a time, and afastpointer moving two nodes at a time. - If there is no cycle,
fastwill eventually reach the end of the structure (represented by-1). - If a cycle exists, both pointers will eventually enter the cycle. Because
fastreduces the relative distance toslowby 1 node in each step inside the loop, they will eventually coincide at the same index.
Part 2: Two Sum in a Sorted Array
To find two elements that sum to a given target in a sorted array:
- Place a
leftpointer at the beginning (index 0) and arightpointer at the end (index len(numbers) - 1). - Calculate the current sum
numbers[left] + numbers[right]:- If the sum matches
target, convert the indices to 1-based ([left + 1, right + 1]) and return. - If the sum is strictly less than
target, incrementleftto increase the total sum. - If the sum is strictly greater than
target, decrementrightto reduce the total sum.
- If the sum matches
Complexity Analysis
-
Time Complexity:
- Cycle Detection: $\mathcal{O}(N)$, where $N$ is the length of
values. Both pointers traverse at most $N$ steps before either meeting or hitting the end. - Two Sum: $\mathcal{O}(M)$, where $M$ is the length of
numbers. Each step advances one pointer inward, taking at most $M$ steps. - Overall Time Complexity: $\mathcal{O}(N + M)$.
- Cycle Detection: $\mathcal{O}(N)$, where $N$ is the length of
-
Space Complexity: $\mathcal{O}(1)$ auxiliary space beyond the output dictionary.
Python Reference Solution
from typing import List, Dict
def solve_two_tasks(values: List[int], cycle_pos: int, numbers: List[int], target: int) -> Dict[str, object]:
n = len(values)
# ---------- Part 1: Simulated Floyd's Cycle Detection ----------
if n == 0 or cycle_pos < 0:
has_cycle = False
else:
def next_index(i: int) -> int:
if i == -1:
return -1
if i + 1 < n:
return i + 1
return cycle_pos
slow = 0
fast = 0
while True:
slow = next_index(slow)
fast = next_index(next_index(fast))
if slow == fast:
has_cycle = (slow != -1)
break
# ---------- Part 2: Two Pointers on Sorted Array ----------
left = 0
right = len(numbers) - 1
pair = []
while left < right:
total = numbers[left] + numbers[right]
if total == target:
pair = [left + 1, right + 1]
break
elif total < target:
left += 1
else:
right -= 1
return {"has_cycle": has_cycle, "two_sum": pair}