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) <= 1000
  • max_modified_substring must execute in strictly sub-cubic time (faster than O(N^3), where N = max(len(s1), len(s2))).
  • Only s1 may have up to one character deleted; s2 remains 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

  1. Understand both tasks

    This interview question pairs two independent exercises:

    1. Task A (Consecutive-Day Endpoint Visits): Given access records (user_id, url, day), find every unique user_id that requested the exact same url on some day d and again on day d + 1.
    2. Task B (One-Deletion Common Substring — judged): Given strings s1 and s2 (each up to length 1000), you may delete at most one character from s1 (s2 cannot be modified). Return the maximum length of a substring—a contiguous, unbroken slice of characters—shared by the resulting s1 and s2, running strictly faster than O(N^3).
  2. 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 Python set solves both issues at once: duplicates collapse automatically, and checking whether the next day's tuple (user_id, url, day + 1) also occurred takes O(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? No
    
    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)
    
  3. 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—s1 unchanged, plus each single-character deletion s1[:del_idx] + s1[del_idx + 1:]—and compute the longest common substring against s2 from scratch for each candidate.

    Finding the longest common substring of two strings of lengths n and m takes O(n * m) work. Repeating that table across n + 1 candidates costs O(n^2 * m)—roughly 1,000 * 1,000 * 1,000 = 10^9 cell updates at the constraint limit, hitting O(N^3). Notice why it wastes work: deleting s1[del_idx] only changes one seam in s1, while all character matches purely to the left or purely to the right of del_idx never changed at all!

  4. Key insight: two pieces meeting at a split point in s2

    Suppose we delete s1[del_idx]. Any common substring of the modified s1 and s2 either: 1. Never crosses del_idx, meaning it was already a substring of the original unmodified s1, OR 2. Bridges across del_idx, gluing a piece of s1 ending right at del_idx - 1 to a piece of s1 starting right at del_idx + 1. Because s2 is not modified, those two pieces must sit side-by-side with zero gap in s2, meeting at some boundary split_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_j
    

    For 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 of s1[:del_idx] and s2[:split_j]. - Right length = longest common prefix of s1[del_idx + 1:] and s2[split_j:].

    If we precompute those two tables once in O(n * m) time, every (del_idx, split_j) bridge check becomes a single O(1) addition!

  5. 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 of s1[:i] and s2[:j]. If the last characters s1[i - 1] and s2[j - 1] match, it extends left_match[i - 1][j - 1] by 1; otherwise it resets to 0 (because substrings must be contiguous).
    • right_match[i][j]: longest common prefix of s1[i:] and s2[j:]. If the first characters s1[i] and s2[j] match, it extends right_match[i + 1][j + 1] by 1; 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) without if guards.

    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
    
  6. Combine 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 shrinks s1 to 5 characters, so only Phase 1 finds length 6. - Phase 2 (delete s1[del_idx]): For every del_idx in 0 .. n - 1 and every split_j in 0 .. m, check left_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_len
    
  7. Walk through Example 1 on the two tables

    Let's trace s1 = "stqorm" (n = 6) and s2 = "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!
    
  8. 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). Filling left_match visits each of the (n + 1) * (m + 1) cells once with an O(1) character comparison, filling right_match does the same backward, and the two maximization loops each visit (n + 1) * (m + 1) or n * (m + 1) pairs in O(1) time—around a few million basic operations at n = m = 1000, far below the O(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. Inserting N tuples into seen_visits and doing one O(1) hash lookup per unique visit takes O(N) expected time, and sorting the U unique user IDs takes O(U log U).
  • Space: O(N) in the worst case to store up to N unique (user_id, url, day) tuples in seen_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 in left_match and right_match remain 0, returning 0 cleanly.
  • All of s1 already appears in s2 ("metric" vs "zzmetriczz", Example 2): Deleting any character shortens s1 to length 5, so Phase 1 (0 deletions) is essential to return 6.
  • Two pieces exist in s2 but are not adjacent ("abXcd" vs "ab_cd"): Because both halves must meet at the same split_j in s2, '_' blocks them from joining and the answer is 2, not 4.
  • Deletion is allowed only in s1 ("abcd" vs "abXcd"): We never skip a character in s2 (split_j is the same index in left_match and right_match), returning 2.
  • Multiple stray characters ("kp_mn_rt" vs "pmnr", Example 3): Only one character can be deleted, bridging at most one gap for length 3 ("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 of s1 to be dropped, returning n - 1 instead of n when s1 is already a substring of s2.
  • 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 in s2.
  • Off-by-one at the deleted character: left_match[del_idx][split_j] ends at s1[del_idx - 1], while right_match[del_idx + 1][split_j] starts at s1[del_idx + 1]. Using left_match[del_idx + 1] accidentally includes the deleted character s1[del_idx].
  • Carrying matches forward on mismatch (solving Longest Common Subsequence): In substrings, when s1[i - 1] != s2[j - 1], the cell must stay 0 rather than taking max(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 of s2 in linear size O(m). After building it once for s2, you can stream each of the n + 1 candidate modifications of s1 through the automaton in O(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): Because left_match[i][j] only depends on (i - 1, j - 1) along diagonal d = i - j and bridges onto diagonal d + 1 = (i + 1) - j of right_match, processing adjacent pairs of diagonals reduces memory from O(n * m) to O(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 whether day + 1 exists, and emits user_id at most once before a final DISTINCT pass. If logs are already partitioned on disk by day, you only need to join adjacent daily partitions day and day + 1 rather 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 same left_match and right_match tables! Substituting s1[i] to match s2[j] consumes one index in both strings rather than zero indices in s2, so each candidate bridge has length left_match[i][j] + 1 + right_match[i + 1][j + 1] over all 0 <= i < n and 0 <= j < m (combined with the 0-edit maximum). Even allowing up to k substitutions stays O(n * m) by scanning each diagonal i - j = const with a sliding window (two pointers advancing along the diagonal while keeping at most k mismatched 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 for day arrives, check both day - 1 and day + 1 so delayed Day d events still match an already-processed Day d + 1 event. Pair this with a watermark—a moving timestamp cutoff estimating how far behind late records can still arrive—to evict state older than 2 days + max_lateness and keep memory bounded.

Follow-up questions

Similar questions

More Sumologic interview questions

All 1 Sumologic questions →