Group anagrams and count string in grid
Company: J.P. Morgan
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates algorithmic problem-solving skills in string processing, hashing/grouping and grid traversal/backtracking, along with the ability to analyze time and space complexity and trade-offs.
Part 1: Group Anagrams
Constraints
- 0 <= len(words) <= 10^4
- 0 <= len(words[i]) <= 100
- Each word contains only lowercase English letters
- Duplicate strings are allowed
Examples
Input: (['eat', 'tea', 'tan', 'ate', 'nat', 'bat'],)
Expected Output: ([['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']], 3)
Explanation: 'eat', 'tea', and 'ate' are anagrams; 'tan' and 'nat' are anagrams; 'bat' stands alone. Group order follows first appearance in the input.
Input: ([],)
Expected Output: ([], 0)
Explanation: An empty input produces no groups.
Hints
- Two words belong in the same group if they have the same character-frequency signature.
- If the result order must be deterministic, store groups in the order each signature first appears.
Part 2: Count Target in Grid
Constraints
- The grid is rectangular
- 0 <= number of rows, number of columns <= 6
- 1 <= len(target) <= 12
- Each grid cell and each character in target is an uppercase English letter
Examples
Input: (['AB', 'CA'], 'ABA')
Expected Output: 2
Explanation: There are exactly two valid paths: (0,0)->(0,1)->(1,1) and the reverse path (1,1)->(0,1)->(0,0).
Input: (['AA', 'AA'], 'AA')
Expected Output: 8
Explanation: Each of the 4 cells can start a path, and each start has 2 orthogonal neighbors, giving 4 * 2 = 8 paths.
Hints
- Use DFS/backtracking starting only from cells that match the first character of the target.
- Keep a visited structure so a path never reuses a cell, and prune early if the grid does not contain enough copies of some character in the target.