Profit, Collinearity, and Identity Merging in Three Parts
Arrays & HashingAuto-graded · 28 test casesLast updated
Tests one-pass array scanning, integer-arithmetic collinear point detection, and union-find graph component grouping in a single combined function.
Problem Statement
You are building a multi-purpose analytics utility that processes two kinds of input at once: a sequence of integer measurements and a list of name-pair relationships. Implement a single function analyze_sequence that solves three independent sub-problems and returns their results together in a dictionary.
Sub-problem 1 — Best Single Buy-Sell Gain (max_profit)
Given the sequence as a list of integers, find the maximum gain achievable by choosing a buy index i and a sell index j such that i < j. If no positive gain exists (including when the list has fewer than two elements), return 0.
Sub-problem 2 — Earliest Collinear Quadruplet (find_collinear_quad)
Treat each element as a 2D point: index t becomes the x-coordinate and sequence[t] becomes the y-coordinate. Find four distinct indices [i, j, k, l] with i < j < k < l such that all four corresponding points lie exactly on the same straight line.
- If several such quadruplets exist, return the lexicographically smallest one.
- If none exists, return
None. - All collinearity checks must use integer arithmetic (cross-multiplication) to avoid floating-point errors.
Sub-problem 3 — Connected Name Groups (group_aliases)
You are given a list of pairs (a, b) meaning that name a and name b refer to the same entity. Treating these pairs as edges in an undirected graph, find every connected component.
- Within each component, sort the names lexicographically.
- Sort the list of components lexicographically by each component's first element.
- A self-pair
("x", "x")produces a singleton group["x"]. - If no pairs are given, return an empty list.
Return Value
Return a single dictionary with exactly these keys:
{
"max_profit": int,
"find_collinear_quad": list[int] | None,
"group_aliases": list[list[str]],
}
Constraints
Shared input — sequence:
0 <= len(sequence) <= 10^5(sub-problem 1)4 <= len(sequence) <= 2000(sub-problem 2; the collinear search only runs within this range)-10^9 <= sequence[t] <= 10^9
Sub-problem 1 — max_profit:
- Values can be negative or very large; assume 64-bit integer arithmetic.
- Return
0for any input where no profitable trade is possible.
Sub-problem 2 — find_collinear_quad:
- Use cross-multiplication for slope comparison: points
(x1,y1),(x2,y2),(x3,y3)are collinear when(y2-y1)*(x3-x1) == (y3-y1)*(x2-x1).
Sub-problem 3 — group_aliases (via pairs):
0 <= len(pairs) <= 5 * 10^4- Each name consists of
1to32lowercase English letters.
Examples
Example 1
Input: analyze_sequence([10, 7, 5, 8, 11, 9], [])
Output: {'max_profit': 6, 'find_collinear_quad': None, 'group_aliases': []}
Example 2
Input: analyze_sequence([9, 8, 7, 5], [])
Output: {'max_profit': 0, 'find_collinear_quad': None, 'group_aliases': []}
Example 3
Input: analyze_sequence([2, 5, 8, 10, 14, 17], [])
Output: {'max_profit': 15, 'find_collinear_quad': [0, 1, 2, 4], 'group_aliases': []}
Example 4
Input: analyze_sequence([0, 0, 0, 0], [['a', 'a']])
Output: {'max_profit': 0, 'find_collinear_quad': [0, 1, 2, 3], 'group_aliases': [['a']]}
Hints
Hint 1
For the max gain, you only ever need to remember one thing as you scan left to right: the smallest value seen so far. Every element to its right is a candidate sell.
Hint 2
For the collinear quadruplet, fix a base index i and hash the reduced slope from i to every later index j. Use gcd to normalize the slope fraction so integer equality replaces floating-point comparison. The moment a slope bucket hits three entries, you have a candidate quadruplet.
Hint 3
For grouping, model the pairs as graph edges and apply union-find. After processing all pairs, collect every name by its root, sort each bucket internally, then sort the bucket list by its first element.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The three sub-problems are fully independent. Each maps to a classic pattern.
Sub-problem 1 — Maximum Gain (One-Pass Scan)
Scan the sequence once from left to right, tracking the lowest value seen so far (best_buy). At every position that is not a new minimum, compute current - best_buy and update the running maximum. Because the running minimum at position j is the best possible buy for a sell at j, the maximum over all j is the global optimum.
Starting the answer at 0 means a decreasing sequence, an empty sequence, or a single element all correctly return 0.
Python integers are arbitrary-precision, so values up to ±10¹² cause no overflow.
Sub-problem 2 — Lexicographically Smallest Collinear Quadruplet
Approach: fix a base index i. Every later index j defines a direction vector (dy, dx) where dx = j - i ≥ 1 and dy = sequence[j] - sequence[i]. Two later points j and k are collinear with i iff their direction vectors are proportional — i.e., the same reduced fraction.
Normalise each vector by dividing both components by gcd(|dy|, dx). Because dx ≥ 1, this divisor is always at least 1, so there is no division-by-zero risk. The result is a canonical integer pair usable as a hash key — no floating-point involved.
Collect later indices into per-slope buckets (in increasing order). The instant a bucket reaches three entries [j1, j2, j3], form the candidate [i, j1, j2, j3]. Keep only the lexicographically smallest candidate seen across all i and all slopes.
Why it is correct: any valid quadruplet [i, j, k, l] means j, k, l all share the same normalised slope from base i, so they land in the same bucket. For a fixed i and line, the first three bucket entries give the lex-smallest quadruplet on that line. Comparing across all bases gives the global lex-minimum.
A concrete note: given sequence = [2, 5, 8, 10, 14, 17], the point at index 4 (y = 14) also lies on the line through indices 0, 1, 2, and 5. The slope bucket for base 0 and reduced slope (3, 1) collects [1, 2, 4, 5] in order. The first three entries produce candidate [0, 1, 2, 4], which is what the judge expects.
Sub-problem 3 — Connected Name Groups (Union-Find)
Model pairs as edges in an undirected graph. Use a dictionary-based Disjoint Set Union:
findlazily initialises unseen names as their own root (setdefault).finduses path halving (two-step skipping) in a loop — no recursion, so deep chains don't hit Python's call-stack limit.unionattaches the root ofbunder the root ofa.
A self-pair ("x", "x") registers x and immediately finds equal roots, so no union is performed; x remains a singleton component — the correct behaviour.
After all unions, group every name by its root, sort each group lexicographically, then sort the list of groups by their first element. Because groups are disjoint, first elements are unique, making the outer ordering deterministic.
Complexity
| Sub-problem | Time | Space |
|---|---|---|
| Max gain | O(n) | O(1) |
| Collinear quad | O(n² log V) — n²/2 pairs, each needs a gcd on values ≤ 2·10⁹ | O(n) per base index |
| Name grouping | O(P · α(N) + N log N · L) — P pairs, N names, L ≤ 32 | O(N) |
For the collinear search at n = 2000, this is roughly 2 × 10⁶ hash operations — well within limits. The slope-bucket dictionary is rebuilt per base, keeping space at O(n).
Edge Cases
- Empty or single-element
sequence: profit is0;range(n - 3)is empty so the quad result isNone. - All equal values: profit is
0; every slope normalises to(0, 1), so a flat-line quadruplet will be found ifn ≥ 4. - Strictly decreasing sequence: every candidate profit is negative; the answer stays
0. - No pairs:
parentstays empty;group_aliasesreturns[]. - Duplicate or redundant pairs: roots are already equal, so the union is a no-op.
Full Solution
from math import gcd
from typing import Dict, List
def analyze_sequence(sequence: List[int], pairs: List[List[str]]) -> Dict[str, object]:
# --- Sub-problem 1: maximum single buy-sell gain ---
best_buy = None
max_profit = 0
for price in sequence:
if best_buy is None or price < best_buy:
best_buy = price
else:
max_profit = max(max_profit, price - best_buy)
# --- Sub-problem 2: lexicographically smallest collinear quadruplet ---
best_quad = None
n = len(sequence)
for i in range(n - 3):
slope_buckets = {}
for j in range(i + 1, n):
dy = sequence[j] - sequence[i]
dx = j - i # always >= 1
divisor = gcd(abs(dy), dx) # always >= 1, no division by zero
slope = (dy // divisor, dx // divisor)
bucket = slope_buckets.setdefault(slope, [])
bucket.append(j)
if len(bucket) == 3: # first three collinear partners found
candidate = [i, bucket[0], bucket[1], bucket[2]]
if best_quad is None or candidate < best_quad:
best_quad = candidate
# --- Sub-problem 3: connected name components via union-find ---
parent: Dict[str, str] = {}
def find(name: str) -> str:
parent.setdefault(name, name)
while parent[name] != name:
parent[name] = parent[parent[name]] # path halving
name = parent[name]
return name
for a, b in pairs:
root_a = find(a)
root_b = find(b)
if root_a != root_b:
parent[root_b] = root_a
components: Dict[str, List[str]] = {}
for name in parent:
components.setdefault(find(name), []).append(name)
group_aliases = [sorted(members) for members in components.values()]
group_aliases.sort(key=lambda members: members[0])
return {
"max_profit": max_profit,
"find_collinear_quad": best_quad,
"group_aliases": group_aliases,
}