Cyclic Array Shifts and CSV Cell Substring Search

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement five utility functions across two independent parts: cyclic list shifting and substring matching inside a plain comma-separated table.

Part 1 — Cyclic List Shifts

Given a list of integers nums of length n and an integer shift count k:

  1. rotate_left(nums: List[int], k: int) -> List[int]: Return a new list produced by shifting every element k steps toward index 0, wrapping elements shifted off the front around to the back. Do not mutate nums.
  2. rotate_right(nums: List[int], k: int) -> List[int]: Return a new list produced by shifting every element k steps toward index n - 1, wrapping elements shifted off the back around to the front. Do not mutate nums.
  3. rotate_right_in_place(nums: List[int], k: int) -> None: Mutate nums directly so its elements are shifted right by k steps using O(1) auxiliary space, and return None.

Shift counts k may be 0, greater than or equal to n, or negative; reduce shifts modulo n so a negative shift moves in the opposite direction. Empty (n == 0) and single-element (n == 1) lists remain unchanged without raising division-by-zero errors.

Part 2 — Substring Search in Plain CSV Cells

Given a string csv_text representing an unquoted table where lines are separated by "\n" and cells within each line are separated by "," (no quoted fields or escape sequences):

  1. find_keyword(csv_text: str, key: str) -> List[Tuple[int, int, int]]: Find every occurrence of key inside individual cells and return (row, col, pos) tuples sorted by (row, col, pos) ascending (0-indexed row, 0-indexed column, and 0-indexed starting character offset inside that cell).
    • Count overlapping matches inside a single cell (for instance, "aa" inside "aaa" matches at offsets 0 and 1).
    • Matches never span across "," or "\n" delimiters. Empty cells and blank lines still occupy their respective column and row indices.
    • Raise ValueError if key == "".
  2. find_keywords(csv_text: str, keys: List[str]) -> List[Tuple[int, int, int, str]]: Search for all patterns in keys and return (row, col, pos, key) tuples.
    • Sort results by (row, col, pos) ascending; when two distinct patterns start at the exact same (row, col, pos), preserve their first-seen relative order in keys.
    • Deduplicate repeated entries in keys so each distinct pattern is reported once per match. Return [] when keys is empty.
    • Raise ValueError if any entry in keys equals "".

Examples

Example 1

Input:

nums = [10, 20, 30, 40, 50, 60]
k = 8

Output:

rotate_left(nums, 8)   # [30, 40, 50, 60, 10, 20]
rotate_right(nums, 8)  # [50, 60, 10, 20, 30, 40]

Explanation: Because len(nums) == 6, shifting by 8 positions wraps around one full cycle plus 8 % 6 = 2 steps. Shifting left by 2 moves [10, 20] to the tail; shifting right by 2 (or calling rotate_right_in_place on a mutable copy) moves [50, 60] to the head while leaving the caller's original nums untouched in rotate_left and rotate_right.

Example 2

Input:

csv_text = "banana,pan\ntan,anana"
key = "ana"

Output:

[(0, 0, 1), (0, 0, 3), (1, 1, 0), (1, 1, 2)]

Explanation: Row 0 splits into "banana" (where "ana" starts at offsets 1 and 3, overlapping on 'a') and "pan" (no hits). Row 1 splits into "tan" (no hits) and "anana" (overlapping hits at offsets 0 and 2).

Example 3

Input:

csv_text = "cart,ca\nscar"
keys = ["car", "ca", "car"]

Output:

[(0, 0, 0, "car"), (0, 0, 0, "ca"), (0, 1, 0, "ca"), (1, 0, 1, "car"), (1, 0, 1, "ca")]

Explanation: Deduplicating keys in first-seen order yields ["car", "ca"]. In cell (0, 0) ("cart"), both "car" and "ca" begin at offset 0, so "car" precedes "ca". Cell (0, 1) ("ca") matches "ca" at offset 0, and cell (1, 0) ("scar") matches both "car" and "ca" at offset 1.

Constraints

  • 0 <= len(nums) <= 10^5
  • -10^12 <= k <= 10^12
  • 0 <= len(csv_text) <= 10^5
  • csv_text contains no quoted delimiters or escape sequences; rows split strictly on "\n" and cells strictly on ",".
  • Any empty search pattern "" (either key == "" or "" in keys) must raise ValueError.

Step-by-step walkthrough

  1. Understand both parts and pin down edge-case contracts

    This problem pairs two foundational tasks — cyclic list shifts and cell-by-cell substring matching — where clean edge-case contracts keep the implementation simple and bug-free.

    • Part 1 (Cyclic list shifts): Shifting left by k moves elements toward index 0 so the first k items wrap around to the back; shifting right by k moves elements toward index n - 1 so the last k items wrap around to the front. Because shifting an n-element list by n steps brings every item back to its starting slot, only the remainder k % n (modulo arithmetic) matters.
    • Part 2 (CSV cell substring search): An unquoted CSV string uses \n between lines and , between columns. We emit (row, col, pos) tuples in row-major order — scanning row 0 from left to right across its columns, then row 1, and so on, and scanning from left to right (pos = 0, 1, ...) inside each cell.

    Our five functions enforce three explicit guarantees: 1. rotate_left and rotate_right return a new list without modifying nums, while rotate_right_in_place demonstrates the O(1) auxiliary-space in-place technique (mutating nums directly). 2. Python's % operator always yields 0 <= k % n < n whenever n > 0, so negative shifts work naturally (rotate_left(nums, -1) behaves like rotate_right(nums, 1)). Empty lists (n == 0) return early before k % 0 can raise ZeroDivisionError. 3. Overlapping substring hits count ("ana" inside "banana" matches at pos = 1 and pos = 3), matches never cross , or \n, and any empty pattern "" raises ValueError.

    from typing import List, Tuple
    
    def rotate_left(nums: List[int], k: int) -> List[int]: ...
    def rotate_right(nums: List[int], k: int) -> List[int]: ...
    def rotate_right_in_place(nums: List[int], k: int) -> None: ...
    def find_keyword(csv_text: str, key: str) -> List[Tuple[int, int, int]]: ...
    def find_keywords(csv_text: str, keys: List[str]) -> List[Tuple[int, int, int, str]]: ...
    
  2. Part 1: O(n) cyclic shift via modular cut point

    Shifting one element at a time inside a loop takes O(n * k) work, which stalls completely when k = 10^12. Instead, treat a cyclic shift as cutting a deck of cards once and swapping the two halves:

    nums = [10, 20, 30, 40, 50, 60],  n = 6,  k = 8  ->  effective shift k % 6 = 2
    
    Left by 2:   cut at index 2              [10, 20 | 30, 40, 50, 60] -> [30, 40, 50, 60, 10, 20]
    Right by 2:  cut at split_index = 6 - 2  [10, 20, 30, 40 | 50, 60] -> [50, 60, 10, 20, 30, 40]
    

    Notice why split_index = n - k is safer than negative slicing nums[-k:]: when k == 0, -0 equals 0, so nums[-0:] copies the entire list instead of an empty suffix, whereas nums[n:] + nums[:n] cleanly concatenates [] + nums into a fresh list!

    def rotate_left(nums: List[int], k: int) -> List[int]:
        """Return a new list equal to nums rotated left by k. nums is not modified."""
        n = len(nums)
        # Guard against n == 0 before modulo so k % 0 never raises ZeroDivisionError.
        if n == 0:
            return []
        # Modulo maps any k (including k >= n or k < 0) into 0 <= k < n.
        k = k % n
        # Left rotation moves the first k items to the back: [A(k) | B(n-k)] -> [B | A].
        return nums[k:] + nums[:k]
    
    
    def rotate_right(nums: List[int], k: int) -> List[int]:
        """Return a new list equal to nums rotated right by k. nums is not modified."""
        n = len(nums)
        if n == 0:
            return []
        k = k % n
        # Using split_index = n - k (instead of -k) stays exact even when k == 0 (nums[n:] is []).
        split_index = n - k
        return nums[split_index:] + nums[:split_index]
    
  3. Part 1 in-place: O(1) extra memory via three reversals

    To shift right in place without allocating O(n) slice copies, partition nums into prefix A (length n - k) and suffix B (length k), so we want [A | B] -> [B | A]. Reversing the whole list flips both blocks AND swaps their order ([B_rev | A_rev]), and reversing each block separately restores its internal order:

    Start (k = 2):          [10, 20, 30, 40 | 50, 60]   (A = [10..40], B = [50,60])
    1) Reverse [0 .. 5]:    [60, 50 | 40, 30, 20, 10]   ([B_rev | A_rev])
    2) Reverse [0 .. 1]:    [50, 60 | 40, 30, 20, 10]   ([B     | A_rev])
    3) Reverse [2 .. 5]:    [50, 60 | 10, 20, 30, 40]   ([B     | A    ])
    

    Each element is swapped at most twice, giving O(n) time and O(1) auxiliary space.

    def _reverse(nums: List[int], lo: int, hi: int) -> None:
        """Reverse nums[lo..hi] inclusive in place using two converging pointers."""
        while lo < hi:
            nums[lo], nums[hi] = nums[hi], nums[lo]
            lo += 1
            hi -= 1
    
    
    def rotate_right_in_place(nums: List[int], k: int) -> None:
        """Rotate nums right by k in place using O(1) extra memory."""
        n = len(nums)
        if n <= 1:
            return
        k = k % n
        if k == 0:
            return
        _reverse(nums, 0, n - 1)
        _reverse(nums, 0, k - 1)
        _reverse(nums, k, n - 1)
    
  4. Part 2: cell-by-cell CSV search with overlapping hits

    Instead of scanning the raw csv_text string and translating flat character indices back into (row, col, pos), split csv_text on "\n" to isolate rows and split each row on "," to isolate cells:

    csv_text = "banana,pan\ntan,anana",  key = "ana"
    
             col 0        col 1
    row 0   "banana"     "pan"
              ^1 ^3       (none)
    row 1   "tan"        "anana"
             (none)       ^0 ^2
    

    Splitting up front gives three immediate benefits: enumerate yields row and col in ascending order, cell.find(key, ...) returns the exact 0-based pos inside that cell, and matches can never bridge across a comma or line break. Restarting cell.find at start + 1 (rather than start + len(key)) catches overlapping matches such as "ana" at offsets 1 and 3 inside "banana". Empty cells ("a,,b") and blank lines ("a\n\nb") split into "", preserving later column and row numbers while yielding zero hits.

    def _positions(cell: str, key: str) -> List[int]:
        """Return every 0-based start index of key inside cell, including overlaps."""
        positions: List[int] = []
        start = cell.find(key)
        while start != -1:
            positions.append(start)
            # Advance by +1 (not +len(key)) so overlapping matches like "aa" in "aaaa" are found.
            start = cell.find(key, start + 1)
        return positions
    
    
    def find_keyword(csv_text: str, key: str) -> List[Tuple[int, int, int]]:
        """Return (row, col, pos) for every occurrence of key, in row-major order."""
        if key == "":
            raise ValueError("key must be a non-empty string")
    
        matches: List[Tuple[int, int, int]] = []
        rows = csv_text.split("\n")
        for row, line in enumerate(rows):
            cells = line.split(",")
            for col, cell in enumerate(cells):
                for pos in _positions(cell, key):
                    matches.append((row, col, pos))
        return matches
    
  5. Part 2 multi-pattern: deduplication and deterministic tie-breaking

    When searching a list of patterns keys, each result tuple (row, col, pos, key) names the matched string. Two subtleties arise within a single cell: 1. Repeated patterns in keys (such as ["car", "ca", "car"]): deduplicate up front with a seen set while preserving first-seen order in unique_keys (and check every entry for ""). 2. Ordering within a cell: if cell = "scar" and keys = ["car", "s"], "s" starts at pos = 0 while "car" starts at pos = 1, so "s" must appear first; and if keys = ["car", "ca"] both match at pos = 1, we break the tie using key_index (their order in unique_keys). Collecting (pos, key_index, key) per cell and sorting handles both rules cleanly.

    def find_keywords(csv_text: str, keys: List[str]) -> List[Tuple[int, int, int, str]]:
        """Return (row, col, pos, key) for every occurrence of any key in row-major order."""
        unique_keys: List[str] = []
        seen = set()
        for key in keys:
            if key == "":
                raise ValueError("keys must be non-empty strings")
            if key not in seen:
                seen.add(key)
                unique_keys.append(key)
    
        matches: List[Tuple[int, int, int, str]] = []
        rows = csv_text.split("\n")
        for row, line in enumerate(rows):
            cells = line.split(",")
            for col, cell in enumerate(cells):
                cell_matches: List[Tuple[int, int, str]] = []
                for key_index, key in enumerate(unique_keys):
                    for pos in _positions(cell, key):
                        cell_matches.append((pos, key_index, key))
                cell_matches.sort()
                for pos, _, key in cell_matches:
                    matches.append((row, col, pos, key))
        return matches
    
  6. Trace the examples step by step

    Example 1 trace on nums = [10, 20, 30, 40, 50, 60] with k = 8: - n = 6, so k = 8 % 6 = 2. - rotate_left: nums[2:] + nums[:2] = [30, 40, 50, 60] + [10, 20] = [30, 40, 50, 60, 10, 20]. - rotate_right: split_index = 6 - 2 = 4, so nums[4:] + nums[:4] = [50, 60] + [10, 20, 30, 40] = [50, 60, 10, 20, 30, 40].

    Example 3 trace on csv_text = "cart,ca\nscar" with keys = ["car", "ca", "car"]:

    unique_keys = ["car" (idx 0), "ca" (idx 1)]
    
    (row=0, col=0) cell="cart":
      key "car" -> pos 0  -> (0, 0, "car")
      key "ca"  -> pos 0  -> (0, 1, "ca")
      sorted    -> (0, 0, 0, "car"), (0, 0, 0, "ca")
    
    (row=0, col=1) cell="ca":
      key "car" -> none;  key "ca" -> pos 0  -> (0, 1, 0, "ca")
    
    (row=1, col=0) cell="scar":
      key "car" -> pos 1; key "ca" -> pos 1  -> (1, 0, 1, "car"), (1, 0, 1, "ca")
    
  7. Complete solution

    from typing import List, Tuple
    
    
    # ---------- Problem A: array rotations ----------
    
    def rotate_left(nums: List[int], k: int) -> List[int]:
        """Return a new list equal to nums rotated left by k. nums is not modified."""
        n = len(nums)
        # Guard against n == 0 before modulo so k % 0 never raises ZeroDivisionError.
        if n == 0:
            return []
        # Modulo maps any k (including k >= n or k < 0) into 0 <= k < n.
        k = k % n
        # Left rotation moves the first k items to the back: [A(k) | B(n-k)] -> [B | A].
        return nums[k:] + nums[:k]
    
    
    def rotate_right(nums: List[int], k: int) -> List[int]:
        """Return a new list equal to nums rotated right by k. nums is not modified."""
        n = len(nums)
        if n == 0:
            return []
        k = k % n
        # Using split_index = n - k (instead of -k) stays exact even when k == 0 (nums[n:] is []).
        split_index = n - k
        return nums[split_index:] + nums[:split_index]
    
    
    def _reverse(nums: List[int], lo: int, hi: int) -> None:
        """Reverse nums[lo..hi] inclusive in place using two converging pointers."""
        while lo < hi:
            nums[lo], nums[hi] = nums[hi], nums[lo]
            lo += 1
            hi -= 1
    
    
    def rotate_right_in_place(nums: List[int], k: int) -> None:
        """Rotate nums right by k in place using O(1) extra memory."""
        n = len(nums)
        if n <= 1:
            return
        k = k % n
        if k == 0:
            return
        # Three-reversal identity on [A(n-k) | B(k)]:
        # 1) reverse whole array -> [B_rev | A_rev]  e.g. [10,20,30,40,50,60] -> [60,50,40,30,20,10]
        _reverse(nums, 0, n - 1)
        # 2) reverse first k     -> [B     | A_rev]  e.g. k=2                 -> [50,60,40,30,20,10]
        _reverse(nums, 0, k - 1)
        # 3) reverse last n - k  -> [B     | A    ]  e.g.                     -> [50,60,10,20,30,40]
        _reverse(nums, k, n - 1)
    
    
    # ---------- Problem B: keyword search in simple CSV ----------
    
    def _positions(cell: str, key: str) -> List[int]:
        """Return every 0-based start index of key inside cell, including overlaps."""
        positions: List[int] = []
        start = cell.find(key)
        while start != -1:
            positions.append(start)
            # Advance by +1 (not +len(key)) so overlapping matches like "aa" in "aaaa" are found.
            start = cell.find(key, start + 1)
        return positions
    
    
    def find_keyword(csv_text: str, key: str) -> List[Tuple[int, int, int]]:
        """Return (row, col, pos) for every occurrence of key, in row-major order."""
        if key == "":
            raise ValueError("key must be a non-empty string")
    
        # matches: list of (row_idx, col_idx, char_offset_in_cell) in row-major order.
        matches: List[Tuple[int, int, int]] = []
        # Splitting by '\n' then ',' isolates cells so matches can never cross ',' or '\n'.
        rows = csv_text.split("\n")
        for row, line in enumerate(rows):
            cells = line.split(",")
            for col, cell in enumerate(cells):
                for pos in _positions(cell, key):
                    matches.append((row, col, pos))
        return matches
    
    
    def find_keywords(csv_text: str, keys: List[str]) -> List[Tuple[int, int, int, str]]:
        """Return (row, col, pos, key) for every occurrence of any key in row-major order."""
        # Phase 1: validate keys and deduplicate while preserving caller's first-seen order.
        unique_keys: List[str] = []
        seen = set()
        for key in keys:
            if key == "":
                raise ValueError("keys must be non-empty strings")
            if key not in seen:
                seen.add(key)
                unique_keys.append(key)
    
        # Phase 2: scan each cell and sort within-cell hits by (pos, key_index) for stable ties.
        matches: List[Tuple[int, int, int, str]] = []
        rows = csv_text.split("\n")
        for row, line in enumerate(rows):
            cells = line.split(",")
            for col, cell in enumerate(cells):
                # cell_matches: list of (pos_in_cell, key_order_idx, key_str) for this cell.
                cell_matches: List[Tuple[int, int, str]] = []
                for key_index, key in enumerate(unique_keys):
                    for pos in _positions(cell, key):
                        cell_matches.append((pos, key_index, key))
                cell_matches.sort()
                for pos, _, key in cell_matches:
                    matches.append((row, col, pos, key))
        return matches
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture cyclic list shifting as cutting a deck of n cards once and swapping the top and bottom packets. Shifting n cards by n steps leaves the deck unchanged, so modulo arithmetic (k % n, the remainder after dividing k by n) collapses even k = 10^12 down to a single cut index: k for a left shift, or n - k for a right shift. When you need an in-place algorithm (mutating the list directly with only a few scalar index variables of extra space), reversing the entire deck flips both packets into their final positions ([A | B] -> [B_rev | A_rev]), and reversing each packet individually restores [B | A]. For CSV cell search, think of the text as a 2D spreadsheet: splitting on \n isolates rows, splitting each row on , isolates cells, and scanning inside each cell naturally visits entries in row-major order (top-to-bottom across rows, left-to-right across columns, and left-to-right inside each cell) without ever matching across cell boundaries.

Shifting a list one step at a time performs k full-list copies for O(n * k) work, which times out whenever k is huge. Likewise, searching the unsplit csv_text string requires error-prone offset bookkeeping to recover (row, col, pos) and risks false hits spanning across , or \n. Reducing k % n and splitting into cells up front avoid both pitfalls cleanly.

Walk through the sample inputs: - Shifts ([10, 20, 30, 40, 50, 60], k = 8): Since 8 % 6 = 2, a left cut at 2 swaps [10, 20] and [30, 40, 50, 60] into [30, 40, 50, 60, 10, 20]. A right cut at 6 - 2 = 4 (or three reversals [10..60] -> [60..10] -> [50,60,40,30,20,10] -> [50,60,10,20,30,40]) produces [50, 60, 10, 20, 30, 40]. - CSV search ("banana,pan\ntan,anana", key = "ana"): Row 0 splits into "banana" (hits at pos = 1 and pos = 3) and "pan" (no hits); Row 1 splits into "tan" (no hits) and "anana" (hits at pos = 0 and pos = 2), yielding [(0, 0, 1), (0, 0, 3), (1, 1, 0), (1, 1, 2)].

Complexity

Let n be len(nums), L be len(csv_text), m be len(key) (or m_max the longest pattern in keys), K be the number of distinct patterns, and M be the total matches returned.

  • rotate_left and rotate_right — O(n) time and O(n) space: Computing k % n takes O(1), and slicing plus concatenating copies each of the n elements once into a new n-element list.
  • rotate_right_in_place — O(n) time and O(1) extra space: Three _reverse passes swap each element at most twice using only two integer pointers lo and hi.
  • find_keyword — O(L * m) worst-case time, O(L + M) space: Splitting csv_text scans every character once (O(L)), and repeated str.find calls compare up to m characters at each of the O(L) cell positions in the worst case; memory holds the split substrings (O(L)) plus M output tuples.
  • find_keywords — O(K * L * m_max + M log M) worst-case time, O(L + K + M) space: Deduplicating keys takes O(total pattern characters), scanning K patterns across all cells takes O(K * L * m_max), and sorting hits per cell adds at most O(M log M) overall.

Edge cases

  • Empty list (n = 0) and single-element list (n = 1): Checking n == 0 (or n <= 1) before k % n prevents ZeroDivisionError on k % 0 and returns [] or [x].
  • k = 0, multiples of n, and huge k (10^12): All reduce via k % n in O(1); computing split_index = n - k in rotate_right ensures k == 0 evaluates nums[n:] + nums[:n] = [] + nums rather than tripping over -0 == 0.
  • Negative k: Python's modulo maps -1 % 4 to 3, turning a left shift by -1 into a right shift by 1 (in C++ or Java where -1 % 4 == -1, normalize via ((k % n) + n) % n).
  • Overlapping substring matches: Advancing cell.find from start + 1 instead of start + len(key) finds all overlapping hits such as (0, 0, 1) and (0, 0, 3) for "ana" in "banana".
  • Empty cells ("a,,b"), blank rows ("a\n\nb"), and trailing \n: split keeps empty "" entries so column and row indices of subsequent cells stay exact.
  • Patterns containing , or \n, and empty pattern "": Patterns containing delimiters naturally yield [] because no split cell contains , or \n; an empty string "" explicitly raises ValueError.

Common mistakes

  • Shifting one element at a time k times: O(n * k) work times out as soon as k is large even when n is small.
  • Swapping left and right slice cut points: Always verify on a small list ([10, 20, 30, 40, 50, 60], k = 2: left starts with nums[2] = 30, right starts with nums[6 - 2] = 50).
  • Returning nums directly when k % n == 0: Aliasing the caller's list means later mutations to the returned list corrupt the caller's input; nums[k:] + nums[:k] always allocates a fresh list.
  • Advancing find by start + len(key): Jumping past the entire match silently skips overlapping occurrences like "ana" inside "anana".
  • Appending all hits for keys[0] inside a cell before all hits for keys[1]: Without sorting cell_matches by (pos, key_index), a match of keys[0] at pos = 4 appears ahead of a match of keys[1] at pos = 0, violating row-major order.

Alternative approaches

  • Index-mapping loop (result[i] = nums[(i + k) % n]): Achieves the same O(n) time and O(n) space without slice allocation temporaries and ports directly to C, Java, or Go.
  • Cyclic replacements ("juggling" algorithm) for in-place shifting: Moves items along gcd(n, k) disjoint index cycles in O(n) time and O(1) extra space with exactly n writes, though cycle termination is easier to get wrong than three reversals.
  • Knuth-Morris-Pratt (KMP) string matching: A linear-time substring algorithm that precomputes a fallback prefix table in O(m) space so scanning a cell of length c takes guaranteed O(c + m) worst-case time even on repetitive strings.

Follow-up questions

  • How would your parser change if cells follow RFC 4180 quoting rules (allowing commas and line breaks inside double quotes)? Splitting directly on \n and , breaks whenever a quoted field contains "Seattle, WA" or an embedded line break. Instead, stream records through Python's standard csv.reader(io.StringIO(csv_text)) (or a small character state machine tracking in_quotes and escaped "" pairs) to obtain logical rows of unquoted cell values, and confirm with the interviewer whether row and pos index logical CSV records/characters or raw byte positions.
  • How would you process a multi-gigabyte CSV file that cannot fit in memory, and how could you parallelize it across cores? Iterate lazily over the file handle line by line (for row, line in enumerate(handle):) stripping trailing \r\n, dropping memory from O(file_size) to O(longest_line), and yield matches from a generator instead of materializing one huge list. To parallelize across W workers, partition the file into W byte ranges snapped to the next \n boundary, have each worker return chunk-local row numbers plus its line count, and add the prefix sum of earlier chunks' line counts to shift local rows into global row indices.
  • How would you optimize find_keywords when the keyword dictionary grows to tens of thousands of patterns? Running cell.find independently for K = 50,000 patterns rescans every cell K times (O(K * L)). Instead, compile the deduplicated patterns once into an Aho-Corasick automaton — a prefix tree (trie) augmented with failure links that jump to the longest proper suffix that is also a pattern prefix on a mismatch — in O(sum of pattern lengths) preprocessing time, then sweep each cell in a single pass in O(L + M) total time (resetting to the root node between cells).

Follow-up questions

Similar questions

More Warner Bros Discovery interview questions

All 2 Warner Bros Discovery questions →