Repeat Log Visitors and Single-Deletion Common Substring
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
This interview prompt consists of two independent data-and-string exercises; the automated judge evaluates max_modified_substring in Task B.
Task A: Consecutive-Day Endpoint Visits
You receive an access log containing (user_id, url, day) tuples, where day is an integer day number. Identify every distinct user_id who accessed the exact same url on some day d and again on the next day d + 1. For instance, given [(10, "/metrics", 4), (20, "/alerts", 4), (10, "/metrics", 5), (20, "/dashboards", 5)], only user 10 requested "/metrics" on both day 4 and day 5, returning [10].
Task B: One-Deletion Common Substring (Judged)
Implement max_modified_substring(s1, s2). Given two strings s1 and s2, you may remove at most one character from s1 (either deleting one character at any index or keeping s1 untouched; s2 cannot be edited). Return the maximum length of a contiguous substring shared by your resulting s1 and s2.
def max_modified_substring(s1: str, s2: str) -> int:
Examples
Example 1
Input: s1 = "stqorm", s2 = "storm"
Output: 5
Explanation: Removing 'q' at index 2 of s1 forms "storm", which matches all 5 characters of s2 contiguously.
Example 2
Input: s1 = "metric", s2 = "zzmetriczz"
Output: 6
Explanation: Choosing zero deletions preserves "metric", which already occurs intact inside s2 with length 6 (deleting any character from s1 would cap the match at 5).
Example 3
Input: s1 = "kp_mn_rt", s2 = "pmnr"
Output: 3
Explanation: Because at most one character may be removed from s1, deleting the first '_' gives "kpmn_rt" (matching "pmn", length 3) and deleting the second '_' gives "kp_mnrt" (matching "mnr", length 3).
Example 4
Input: s1 = "uv", s2 = "wxyz"
Output: 0
Explanation: The two strings share no characters, so the longest shared contiguous substring has length 0.
Constraints
0 <= len(s1), len(s2) <= 1000max_modified_substringmust execute in strictly sub-cubic time (faster thanO(N^3), whereN = max(len(s1), len(s2))).- Only
s1may have up to one character deleted;s2remains unmodified, and common matches must be contiguous substrings rather than non-contiguous subsequences. - In Task A, log records may contain repeated hits on the same day and arrive in arbitrary order.
Step-by-step walkthrough
Understand both tasks
This interview question pairs two independent exercises:
- Task A (Consecutive-Day Endpoint Visits): Given access records
(user_id, url, day), find every uniqueuser_idthat requested the exact sameurlon some daydand again on dayd + 1. - Task B (One-Deletion Common Substring — judged): Given strings
s1ands2(each up to length1000), you may delete at most one character froms1(s2cannot be modified). Return the maximum length of a substring—a contiguous, unbroken slice of characters—shared by the resultings1ands2, running strictly faster thanO(N^3).
- Task A (Consecutive-Day Endpoint Visits): Given access records
Solve Task A with a hash set of visits
Log files can contain repeated hits on the same day and arrive in arbitrary order. Storing every
(user_id, url, day)tuple in a Pythonsetsolves both issues at once: duplicates collapse automatically, and checking whether the next day's tuple(user_id, url, day + 1)also occurred takesO(1)average time:Input logs: [(10, "/metrics", 4), (20, "/alerts", 4), (10, "/metrics", 5), (20, "/dashboards", 5)] seen_visits set: (10, "/metrics", 4) --> is (10, "/metrics", 5) in seen_visits? YES -> add user 10 (20, "/alerts", 4) --> is (20, "/alerts", 5) in seen_visits? No (10, "/metrics", 5) --> is (10, "/metrics", 6) in seen_visits? No (20, "/dashboards", 5) --> is (20, "/dashboards", 6) in seen_visits? Nodef users_with_next_day_repeat(logs: List[Tuple[int, str, int]]) -> List[int]: """Task A: Return sorted unique user_ids who visited the same URL on day d and day d + 1.""" # seen_visits: set of unique (user_id, url, day) tuples, e.g. {(10, "/metrics", 4), ...} # Deduplicating into a set ignores repeated same-day hits and arbitrary log ordering. seen_visits: Set[Tuple[int, str, int]] = set() for user_id, url, day in logs: seen_visits.add((user_id, url, day)) qualifying_users: Set[int] = set() for user_id, url, day in seen_visits: if (user_id, url, day + 1) in seen_visits: qualifying_users.add(user_id) return sorted(qualifying_users)See why brute force on Task B takes O(N^3) time
A tempting first try for Task B is to construct every candidate string—
s1unchanged, plus each single-character deletions1[:del_idx] + s1[del_idx + 1:]—and compute the longest common substring againsts2from scratch for each candidate.Finding the longest common substring of two strings of lengths
nandmtakesO(n * m)work. Repeating that table acrossn + 1candidates costsO(n^2 * m)—roughly1,000 * 1,000 * 1,000 = 10^9cell updates at the constraint limit, hittingO(N^3). Notice why it wastes work: deletings1[del_idx]only changes one seam ins1, while all character matches purely to the left or purely to the right ofdel_idxnever changed at all!Key insight: two pieces meeting at a split point in s2
Suppose we delete
s1[del_idx]. Any common substring of the modifieds1ands2either: 1. Never crossesdel_idx, meaning it was already a substring of the original unmodifieds1, OR 2. Bridges acrossdel_idx, gluing a piece ofs1ending right atdel_idx - 1to a piece ofs1starting right atdel_idx + 1. Becauses2is not modified, those two pieces must sit side-by-side with zero gap ins2, meeting at some boundarysplit_j:s1 (delete s1[del_idx]): ... [ left piece ending at del_idx - 1 ] X [ right piece starting at del_idx + 1 ] ... (cut) s2 (unmodified, meeting at split_j): ... [ s2[... : split_j] ] [ s2[split_j : ...] ] ... ^ split_jFor a fixed
(del_idx, split_j)pair, how far can the match stretch left, and how far can it stretch right? - Left length = longest common suffix ofs1[:del_idx]ands2[:split_j]. - Right length = longest common prefix ofs1[del_idx + 1:]ands2[split_j:].If we precompute those two tables once in
O(n * m)time, every(del_idx, split_j)bridge check becomes a singleO(1)addition!Precompute left_match (forward) and right_match (backward)
We build two
(n + 1) x (m + 1)dynamic programming tables (each cell reuses one neighboring diagonal cell):left_match[i][j]: longest common suffix ofs1[:i]ands2[:j]. If the last characterss1[i - 1]ands2[j - 1]match, it extendsleft_match[i - 1][j - 1]by1; otherwise it resets to0(because substrings must be contiguous).right_match[i][j]: longest common prefix ofs1[i:]ands2[j:]. If the first characterss1[i]ands2[j]match, it extendsright_match[i + 1][j + 1]by1; we loop backward from the ends of both strings so[i + 1][j + 1]is already computed.
Adding a border row and column of
0s handles empty prefixes (i = 0,j = 0) and empty suffixes (i = n,j = m) withoutifguards.def build_common_suffix_table(s1: str, s2: str) -> List[List[int]]: """Build left_match[i][j] = longest common suffix length of s1[:i] and s2[:j].""" n, m = len(s1), len(s2) # Row 0 and column 0 stay 0 because an empty prefix shares 0 characters with anything. left_match = [[0] * (m + 1) for _ in range(n + 1)] for i in range(1, n + 1): for j in range(1, m + 1): if s1[i - 1] == s2[j - 1]: left_match[i][j] = left_match[i - 1][j - 1] + 1 return left_match def build_common_prefix_table(s1: str, s2: str) -> List[List[int]]: """Build right_match[i][j] = longest common prefix length of s1[i:] and s2[j:].""" n, m = len(s1), len(s2) # Row n and column m stay 0 because an empty suffix shares 0 characters with anything. right_match = [[0] * (m + 1) for _ in range(n + 1)] # Loop backward so right_match[i + 1][j + 1] is ready before computing right_match[i][j]. for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): if s1[i] == s2[j]: right_match[i][j] = right_match[i + 1][j + 1] + 1 return right_matchCombine both tables in O(n * m) time
Now we take the maximum across two quick scans: - Phase 1 (0 deletions): Take the largest entry in
left_match. Do not skip this! In Example 2 (s1 = "metric",s2 = "zzmetriczz"), every 1-character deletion shrinkss1to 5 characters, so only Phase 1 finds length6. - Phase 2 (deletes1[del_idx]): For everydel_idxin0 .. n - 1and everysplit_jin0 .. m, checkleft_match[del_idx][split_j] + right_match[del_idx + 1][split_j].def max_modified_substring(s1: str, s2: str) -> int: """Task B: Longest substring of s1 (after deleting <= 1 char) that also appears in s2.""" n, m = len(s1), len(s2) left_match = build_common_suffix_table(s1, s2) right_match = build_common_prefix_table(s1, s2) # Phase 1 (0 deletions): plain longest common substring of unmodified s1 and s2. # Needed because if all of s1 already matches s2, deleting any character shrinks s1 by 1. best_len = 0 for i in range(n + 1): for j in range(m + 1): if left_match[i][j] > best_len: best_len = left_match[i][j] # Phase 2 (1 deletion): delete s1[del_idx] and glue the piece ending at del_idx - 1 # with the piece starting at del_idx + 1 so they meet side-by-side at split_j in s2. for del_idx in range(n): for split_j in range(m + 1): bridged_len = left_match[del_idx][split_j] + right_match[del_idx + 1][split_j] if bridged_len > best_len: best_len = bridged_len return best_lenWalk through Example 1 on the two tables
Let's trace
s1 = "stqorm"(n = 6) ands2 = "storm"(m = 5):Phase 1 (no deletion): Longest common substring of "stqorm" and "storm" is "orm" -> best_len = 3. Phase 2 at del_idx = 2 (delete s1[2] = 'q') and split_j = 2: s1[:2] = "st" vs s2[:2] = "st" --> left_match[2][2] = 2 s1[3:] = "orm" vs s2[2:] = "orm" --> right_match[3][2] = 3 --------------------- bridged_len = 5 ("storm") Contrast with s1 = "abXcd" and s2 = "ab_cd" at del_idx = 2 (delete 'X'): - At split_j = 2: left_match[2][2] = 2 ("ab"), but s2[2:] = "_cd" starts with '_', so right_match[3][2] = 0 -> total = 2 + 0 = 2. - At split_j = 3: s2[:3] = "ab_" ends with '_', so left_match[2][3] = 0, and right_match[3][3] = 2 ("cd") -> total = 0 + 2 = 2. Requiring the SAME split_j prevents gluing "ab" and "cd" across '_' in s2!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def users_with_next_day_repeat(logs: List[Tuple[int, str, int]]) -> List[int]: """Task A: Return sorted unique user_ids who visited the same URL on day d and day d + 1.""" # seen_visits: set of unique (user_id, url, day) tuples, e.g. {(10, "/metrics", 4), ...} # Deduplicating into a set ignores repeated same-day hits and arbitrary log ordering. seen_visits: Set[Tuple[int, str, int]] = set() for user_id, url, day in logs: seen_visits.add((user_id, url, day)) qualifying_users: Set[int] = set() for user_id, url, day in seen_visits: if (user_id, url, day + 1) in seen_visits: qualifying_users.add(user_id) return sorted(qualifying_users) def build_common_suffix_table(s1: str, s2: str) -> List[List[int]]: """Build left_match[i][j] = longest common suffix length of s1[:i] and s2[:j].""" n, m = len(s1), len(s2) # Row 0 and column 0 stay 0 because an empty prefix shares 0 characters with anything. left_match = [[0] * (m + 1) for _ in range(n + 1)] for i in range(1, n + 1): for j in range(1, m + 1): if s1[i - 1] == s2[j - 1]: left_match[i][j] = left_match[i - 1][j - 1] + 1 return left_match def build_common_prefix_table(s1: str, s2: str) -> List[List[int]]: """Build right_match[i][j] = longest common prefix length of s1[i:] and s2[j:].""" n, m = len(s1), len(s2) # Row n and column m stay 0 because an empty suffix shares 0 characters with anything. right_match = [[0] * (m + 1) for _ in range(n + 1)] # Loop backward so right_match[i + 1][j + 1] is ready before computing right_match[i][j]. for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): if s1[i] == s2[j]: right_match[i][j] = right_match[i + 1][j + 1] + 1 return right_match def max_modified_substring(s1: str, s2: str) -> int: """Task B: Longest substring of s1 (after deleting <= 1 char) that also appears in s2.""" n, m = len(s1), len(s2) left_match = build_common_suffix_table(s1, s2) right_match = build_common_prefix_table(s1, s2) # Phase 1 (0 deletions): plain longest common substring of unmodified s1 and s2. # Needed because if all of s1 already matches s2, deleting any character shrinks s1 by 1. best_len = 0 for i in range(n + 1): for j in range(m + 1): if left_match[i][j] > best_len: best_len = left_match[i][j] # Phase 2 (1 deletion): delete s1[del_idx] and glue the piece ending at del_idx - 1 # with the piece starting at del_idx + 1 so they meet side-by-side at split_j in s2. for del_idx in range(n): for split_j in range(m + 1): bridged_len = left_match[del_idx][split_j] + right_match[del_idx + 1][split_j] if bridged_len > best_len: best_len = bridged_len return best_len✅ Submit now — all tests should pass.
Intuition & how it works
A substring is a contiguous run of adjacent characters inside a string (unlike a subsequence, which is allowed to skip over characters). For Task B, imagine s1 is a paper ribbon with one unwanted knot in the middle and s2 is a fixed wooden ruler: if you snip out one square s1[del_idx] and tape the left ribbon end (s1[:del_idx]) directly to the right ribbon start (s1[del_idx + 1:]), the taped ribbon matches s2 wherever both halves line up flush at the exact same mark split_j on the ruler. We find how far each half stretches using dynamic programming (a technique that fills a table of small subproblem answers in order so each cell reuses a neighbor in O(1) time). For Task A, putting every (user_id, url, day) log record into a hash set (an unordered collection that checks membership in O(1) average time) lets us ask for each visit whether (user_id, url, day + 1) also happened.
The naive approach fails on both tasks. In Task A, comparing only consecutive lines in the input log misses matches whenever different users are interleaved or events arrive out of order. In Task B, explicitly deleting each character s1[0], s1[1], ..., s1[n - 1] and running a full O(n * m) longest-common-substring grid from scratch for every candidate takes O(n^2 * m) time—about 10^9 operations when both strings have length 1000, repeating nearly identical prefix and suffix comparisons 1000 times.
Walk through Example 1 on s1 = "stqorm" and s2 = "storm":
1. Forward table left_match records that s1[:2] = "st" and s2[:2] = "st" share a common suffix of length left_match[2][2] = 2.
2. Backward table right_match records that s1[3:] = "orm" and s2[2:] = "orm" share a common prefix of length right_match[3][2] = 3.
3. Without deleting anything, the best single match in left_match has length 3 ("orm").
4. Deleting s1[2] = 'q' (del_idx = 2) and meeting at split_j = 2 in s2 glues left_match[2][2] + right_match[3][2] = 2 + 3 = 5 ("storm"), so the function returns 5.
Complexity
For Task B, let n = len(s1) and m = len(s2):
- Time:
O(n * m). Fillingleft_matchvisits each of the(n + 1) * (m + 1)cells once with anO(1)character comparison, fillingright_matchdoes the same backward, and the two maximization loops each visit(n + 1) * (m + 1)orn * (m + 1)pairs inO(1)time—around a few million basic operations atn = m = 1000, far below theO(N^3)threshold. - Space:
O(n * m). Both 2D tables store(n + 1) * (m + 1)integers in memory.
For Task A, let N be the number of log entries and U be the number of qualifying users (U <= N):
- Time:
O(N + U log U)expected. InsertingNtuples intoseen_visitsand doing oneO(1)hash lookup per unique visit takesO(N)expected time, and sorting theUunique user IDs takesO(U log U). - Space:
O(N)in the worst case to store up toNunique(user_id, url, day)tuples inseen_visits.
Edge cases
- Empty or disjoint strings (
""or"uv"vs"wxyz"): When either string is empty or their alphabets share nothing (Example 4), all entries inleft_matchandright_matchremain0, returning0cleanly. - All of
s1already appears ins2("metric"vs"zzmetriczz", Example 2): Deleting any character shortenss1to length5, so Phase 1 (0 deletions) is essential to return6. - Two pieces exist in
s2but are not adjacent ("abXcd"vs"ab_cd"): Because both halves must meet at the samesplit_jins2,'_'blocks them from joining and the answer is2, not4. - Deletion is allowed only in
s1("abcd"vs"abXcd"): We never skip a character ins2(split_jis the same index inleft_matchandright_match), returning2. - Multiple stray characters (
"kp_mn_rt"vs"pmnr", Example 3): Only one character can be deleted, bridging at most one gap for length3("pmn"or"mnr"). - Task A duplicate or unsorted logs: Deduplicating
(user_id, url, day)in a set handles repeated hits on the same day and arbitrary chronological order.
Common mistakes
- Omitting the 0-deletion pass: Checking only
left_match[del_idx][split_j] + right_match[del_idx + 1][split_j]forces at least one character ofs1to be dropped, returningn - 1instead ofnwhens1is already a substring ofs2. - Maximizing left and right matches independently: Computing
max_j(left_match[del_idx][j]) + max_k(right_match[del_idx + 1][k])glues pieces from two different places ins2. - Off-by-one at the deleted character:
left_match[del_idx][split_j]ends ats1[del_idx - 1], whileright_match[del_idx + 1][split_j]starts ats1[del_idx + 1]. Usingleft_match[del_idx + 1]accidentally includes the deleted characters1[del_idx]. - Carrying matches forward on mismatch (solving Longest Common Subsequence): In substrings, when
s1[i - 1] != s2[j - 1], the cell must stay0rather than takingmax(dp[i - 1][j], dp[i][j - 1]). - Re-running DP from scratch for each deletion: Correct, but runs in
O(n^2 * m)(O(N^3)) and exceeds the complexity target.
Alternative approaches
- Suffix automaton (
O(n^2 + m)time,O(m)space): A suffix automaton is a compact directed graph that recognizes every substring ofs2in linear sizeO(m). After building it once fors2, you can stream each of then + 1candidate modifications ofs1through the automaton inO(n)time each (O(n^2 + m)total), though it requires substantially more code than two simple 2D tables. - Diagonal-by-diagonal scan (
O(min(n, m))space): Becauseleft_match[i][j]only depends on(i - 1, j - 1)along diagonald = i - jand bridges onto diagonald + 1 = (i + 1) - jofright_match, processing adjacent pairs of diagonals reduces memory fromO(n * m)toO(min(n, m)).
Follow-up questions
- How would you scale the consecutive-day visit check across a cluster when processing billions of log records? Use a distributed MapReduce / Spark shuffle (a parallel step that routes records with the same key to the same worker node) keyed on
(user_id, url), applying a map-side combiner first to drop duplicate(user_id, url, day)hits locally before network transfer. Each worker receives the distinct days for one(user_id, url)pair—avoiding hot-spot skew from heavy users who browse thousands of endpoints—checks whetherday + 1exists, and emitsuser_idat most once before a finalDISTINCTpass. If logs are already partitioned on disk byday, you only need to join adjacent daily partitionsdayandday + 1rather than shuffling all historical traffic at once. - How do the algorithm and time complexity change if you may substitute one character in s1 instead of deleting one? Both time and space stay
O(n * m)using the exact sameleft_matchandright_matchtables! Substitutings1[i]to matchs2[j]consumes one index in both strings rather than zero indices ins2, so each candidate bridge has lengthleft_match[i][j] + 1 + right_match[i + 1][j + 1]over all0 <= i < nand0 <= j < m(combined with the 0-edit maximum). Even allowing up toksubstitutions staysO(n * m)by scanning each diagonali - j = constwith a sliding window (two pointers advancing along the diagonal while keeping at mostkmismatched characters inside the window). - What changes are needed when access log events are ingested out of timestamp order? For offline batch jobs, our hash-set solution already ignores arrival order completely because all records are loaded before checking
day + 1. In a live stream processor (such as Apache Flink), maintain state keyed by(user_id, url)storing the set of active days seen recently, and whenever an event fordayarrives, check bothday - 1andday + 1so delayed Daydevents still match an already-processed Dayd + 1event. Pair this with a watermark—a moving timestamp cutoff estimating how far behind late records can still arrive—to evict state older than2 days + max_latenessand keep memory bounded.
Follow-up questions
- How would you scale the consecutive-day visit check across a cluster when processing billions of log records?
- How do the algorithm and time complexity change if you may substitute one character in s1 instead of deleting one?
- What changes are needed when access log events are ingested out of timestamp order?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array