Grok 4.1 Fast· xai
Frontier Reasoning Traces
Write an algorithm to compute the convex hull of a set of points.
- User
Write an algorithm to compute the convex hull of a set of points.
- Assistant
def convex_hull(points): """ Computes the convex hull of a set of 2D points using Andrew's monotone chain algorithm. Args: points: List of tuples (x, y) representing the points. Returns: List of points forming the convex hull in counterclockwise order. Time Complexity: O(n log n) due to sorting. Space Complexity: O(n). """ if len(points) <= 1: return points # Step 1: Sort points by x-coordinate, then by y-coordinate points = sorted(set(points)) # Remove duplicates and sort if len(points) <= 1: return points def cross(o, a, b): """Compute the cross product (o->a) x (o->b) to determine turn direction.""" return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) # Step 2: Build lower hull lower = [] for p in points: while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0: lower.pop() lower.append(p) # Step 3: Build upper hull upper = [] for p in reversed(points): while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0: upper.pop() upper.append(p) # Step 4: Combine lower and upper hulls, removing the last point of each (duplicates) return lower[:-1] + upper[:-1] # Example usage: # points = [(0, 0), (2, -2), (1, 1), (2, 2), (3, 1), (1, 0)] # hull = convex_hull(points) # print(hull) # Output: [(0, 0), (2, -2), (3, 1), (2, 2)]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.