KatInterview

Dual Pointer Assessment: Loop Detection and Ordered Pair Sum

Linked ListsAuto-graded · 21 test cases
EasyAuto-gradedLinked Listslinked-liststwo-pointersarrays

Last 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 i normally points to node i + 1 for 0 <= i < len(values) - 1.
  • The tail node (len(values) - 1) points back to index cycle_pos. If cycle_pos == -1, the tail points to null (end of list, no cycle).
  • An empty array values has 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] with index1 < index2.
  • You may assume that numbers contains 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] <= 1000
  • numbers is 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.