KatInterview

Cyclic Shifts and Cell-Level Keyword Lookup in CSV Text

Arrays & HashingModel answer
MediumModel answerArrays & Hashingarray-rotationmodular-arithmeticstring-search

Last 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.

  1. Write rotateLeft(nums, k), which gives back the array after every element has moved k places toward the front, with the elements that fall off the front wrapping around to the back.
  2. Write rotateRight(nums, k), which does the mirror operation, moving elements k places toward the back.

Rules:

  • k may exceed n. Treat it as k mod n.
  • Handle n = 0 and n = 1 correctly.
  • 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 index
  • col: 0-based column index
  • pos: 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.