Cyclic Shifts and Cell-Level Keyword Lookup in CSV Text
Arrays & HashingModel answerLast updated
Shift an integer array left or right by k using modular arithmetic, then locate every occurrence of one or more keywords in a simple CSV string, reporting row, column and offset in the cell.
This exercise has two independent parts. Write a clear solution for each, and state your assumptions out loud.
Part A: Cyclic shift of an array
You receive an integer array nums with n elements and an integer k.
- Write
rotateLeft(nums, k), which gives back the array after every element has movedkplaces toward the front, with the elements that fall off the front wrapping around to the back. - Write
rotateRight(nums, k), which does the mirror operation, moving elementskplaces toward the back.
Rules:
kmay exceedn. Treat it ask mod n.- Handle
n = 0andn = 1correctly. - Say explicitly whether your function changes the input or returns a fresh array.
Example: for nums = [1,2,3,4,5] and k = 2
- shifting left gives
[3,4,5,1,2] - shifting right gives
[4,5,1,2,3]
Part B: Keyword lookup in CSV text
You get a whole CSV document as one string csvText.
- Rows are separated by
\n. - Cells within a row are separated by
,. - The format is plain: no quoted fields and no escaped commas.
Given a keyword key, report every place where it appears. Each report holds:
row: 0-based row indexcol: 0-based column indexpos: 0-based index inside that cell where the match starts
Results must come out in row-major order (by row, then column, then position).
Example: csvText = "foo,bar\nxxfood,barfoo" with key = "foo" yields
- row 0, col 0, pos 0
- row 1, col 0, pos 2
- row 1, col 1, pos 3
The exact output shape is up to you as long as it contains row, col and pos.
Extension
Generalize the function to take a list of keywords and report matches for any of them. You may add the matched keyword to each result.
What to discuss
- Whether you rotate in place or build a new array, and the cost of each.
- How you handle overlapping matches, empty keywords and empty cells.
- How the multi-keyword version scales as the number of keywords grows.
Hints
Hint 1
For Part A, a left shift by k is just the suffix starting at index k followed by the prefix before it. First reduce k with k mod n, and check n = 0 before doing so to avoid dividing by zero.
Hint 2
To get O(1) extra space in Part A, reverse the whole array, then reverse the first k items and the last n-k items separately. A left shift by k equals a right shift by n-k.
Hint 3
For Part B, split into rows and then cells, and search inside each cell on its own so a match can never straddle a comma or newline. After a hit at index p, resume the search at p+1 to count overlapping matches, and decide up front what an empty keyword should return.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part A: Cyclic shift
Approach
A shift is a cut and swap. After normalizing k = k % n:
- Left by
k:nums[k:] + nums[:k] - Right by
k:nums[n-k:] + nums[:n-k], which equals a left shift byn - k.
Check n == 0 first and return an empty array, because k % 0 fails. If n == 1 or k % n == 0, the result equals the input.
Contract. The slicing versions return a new list and leave the input untouched. Say this explicitly.
In-place variant (O(1) extra space)
Reasoning: reversing the concatenation AB gives rev(B) rev(A). Reversing each piece again gives BA.
To shift right by k:
- Reverse the entire array.
- Reverse indices
0..k-1. - Reverse indices
k..n-1.
Trace with [1,2,3,4,5], k=2: [5,4,3,2,1], then [4,5,3,2,1], then [4,5,1,2,3]. For a left shift, call the right shift with n - (k % n).
| Version | Time | Extra space |
|---|---|---|
| Slicing | O(n) | O(n) |
| Three reversals | O(n) | O(1) |
Common mistakes
- Dividing by zero when
n == 0. - Forgetting the modulo, so
k > nbreaks slices or loops. - Mixing up the direction of a right shift (it is the suffix of length
kthat moves to the front). - Silently mutating the caller's array when the contract promised a copy.
Part B: Keyword search in CSV
Approach
- Split on
\nto get rows. - Split each row on
,to get cells. - In each cell, collect every start index of the key by calling
findrepeatedly, restarting athit + 1.
Looping rows, then columns, then increasing positions yields row-major order without sorting.
Decisions to state
- Overlaps count.
"aa"in"aaaa"hits at 0, 1 and 2. For non-overlapping matching, restart athit + len(key). - Matches stay inside one cell. Per-cell searching enforces that. A keyword containing
,or\ncan therefore never match. - Empty keyword returns nothing. Otherwise it matches at every index and carries no meaning.
- Case-sensitive by default. For case-insensitive search, lowercase both sides (positions stay valid for most ASCII data).
- Line endings. Strip a trailing
\rfor\r\ninput. A trailing newline makes an empty last row, which has no matches and is harmless. - Empty cells still occupy a column index, so
",,"has three columns.
Multi-keyword variant
Deduplicate the keywords and drop empty ones. For each cell, gather (pos, keyword) pairs for every keyword and sort them. Since sorting happens within a cell, global row-major order is preserved. Each result also carries the matched keyword.
Code
from typing import List, Dict, Tuple, Iterable
def rotate_left(nums: List[int], k: int) -> List[int]:
n = len(nums)
if n == 0:
return []
k %= n
return nums[k:] + nums[:k]
def rotate_right(nums: List[int], k: int) -> List[int]:
n = len(nums)
if n == 0:
return []
k %= n
return nums[n - k:] + nums[:n - k]
def _rev(a: List[int], i: int, j: int) -> None:
while i < j:
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
def rotate_right_in_place(nums: List[int], k: int) -> None:
n = len(nums)
if n == 0:
return
k %= n
_rev(nums, 0, n - 1)
_rev(nums, 0, k - 1)
_rev(nums, k, n - 1)
def rotate_left_in_place(nums: List[int], k: int) -> None:
n = len(nums)
if n == 0:
return
rotate_right_in_place(nums, n - (k % n))
def _cells(text: str) -> Iterable[Tuple[int, int, str]]:
for r, line in enumerate(text.split("\n")):
if line.endswith("\r"):
line = line[:-1]
for c, cell in enumerate(line.split(",")):
yield r, c, cell
def _all_starts(cell: str, key: str) -> List[int]:
out = []
i = cell.find(key)
while i != -1:
out.append(i)
i = cell.find(key, i + 1)
return out
def find_keyword(csv_text: str, key: str) -> List[Dict[str, int]]:
if not key:
return []
return [{"row": r, "col": c, "pos": p}
for r, c, cell in _cells(csv_text)
for p in _all_starts(cell, key)]
def find_keywords(csv_text: str, keys: List[str]) -> List[Dict[str, object]]:
uniq = [k for k in dict.fromkeys(keys) if k]
res = []
for r, c, cell in _cells(csv_text):
hits = sorted((p, k) for k in uniq for p in _all_starts(cell, k))
for p, k in hits:
res.append({"row": r, "col": c, "pos": p, "key": k})
return res
Correctness
Every occurrence lies wholly in exactly one cell, and each cell is visited once. find(key, start) returns the leftmost match at or after start, and advancing by one skips no start index, so all matches are found in increasing order.
Complexity
Let N be the text length, m the keyword length and K the number of keywords.
- Splitting: O(N) time and space.
- Single keyword:
findis fast in practice, but the worst case is O(N·m), for example"aaaa..."searched for"aa..ab". Using KMP or the Z-function per cell guarantees O(N + m). - Multiple keywords with the simple loop: O(K·N·m) worst case.
- Better: build an Aho-Corasick automaton over all keywords and scan each cell once, giving O(N + Σmᵢ + matches). Collecting matches per cell and sorting by
(pos, keyword)keeps the ordering deterministic.
Edge cases
- Empty
csvTextis one empty row with no matches. - A keyword longer than a cell is skipped naturally.
- Duplicate keywords must be deduplicated, or the same match is reported twice.
- Test with overlapping patterns, empty cells, a trailing newline and
\r\ninput.