Implement distinct islands and sliding maxima
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Implement distinct islands and sliding maxima states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Count Distinct Island Shapes
Constraints
- 1 <= number of rows, columns (grid may also be empty -> return 0)
- grid[i][j] is 0 (water) or 1 (land)
- Connectivity is 4-directional (no diagonals)
- Translation-equivalent islands count as one shape; rotations/reflections are distinct
Examples
Input: ([[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]],)
Expected Output: 1
Explanation: Two 2x2 square islands have the same shape after translation, so there is 1 distinct shape.
Input: ([[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]],)
Expected Output: 3
Explanation: An L-shape (top-left), a single-cell island plus an L (right side), and a horizontal domino — three distinct shapes after deduping translation-equivalent ones.
Hints
- Anchor each island's shape to the coordinates of its first-visited cell by storing (r - base_r, c - base_c) for every land cell. This makes the signature translation-invariant.
- Always traverse the island in a deterministic order (e.g., fixed DFS direction order) so identical shapes yield identical coordinate sequences.
- Store each shape signature (a tuple of relative coordinates) in a hash set; the count of distinct shapes is the set size.
- For the rotation/reflection extension, compute all 8 dihedral transformations of the coordinate set, normalize each to the origin, and key on the lexicographically smallest one.
Sliding Window Maximum
Constraints
- 1 <= k <= nums.length (this solution also clamps k > len(nums) and returns [] for empty input)
- nums may contain negative numbers, zeros, and duplicates
- Return one maximum per window, in left-to-right order
Examples
Input: ([1,3,-1,-3,5,3,6,7], 3)
Expected Output: [3, 3, 5, 5, 6, 7]
Explanation: Windows [1,3,-1]->3, [3,-1,-3]->3, [-1,-3,5]->5, [-3,5,3]->5, [5,3,6]->6, [3,6,7]->7.
Input: ([1], 1)
Expected Output: [1]
Explanation: A single-element window returns that element.
Hints
- Maintain a deque of indices (not values) so you can tell when the front element has slid out of the current window.
- Keep the deque values in decreasing order: before pushing index i, pop every back index whose value is <= nums[i], since they can never be a future window maximum.
- The front of the deque is always the index of the current window's maximum — emit nums[deque.front] once you have seen at least k elements.
- Each index enters and leaves the deque at most once, which is the key to the overall O(n) time bound versus a heap's O(n log k).