Posts

Showing posts with the label kmp

HackerRank - Search in a 2-D grid

Image
Today, I managed to complete HackerRank 's Grid Search albeit with a little difficulty. In a nutshell, the problem requires us to find a 2-D rectangular pattern in a 2-D rectangular grid. All contents of the pattern and the grid are digits from 0-9. For example: The given grid is: 1 2 3 4 5 6 7 8 9 0 0 9 8 7 6 5 4 3 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 The given pattern is: 8 7 6 5 4 3 1 1 1 1 1 1 1 1 1 1 1 1 It is not difficult to tell that the pattern exists in the center of the grid (highlighted in red): 1 2 3 4 5 6 7 8 9 0 0 9 8 7 6 5 4 3 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 The grid's dimensions can be at most 1000 * 1000 and the pattern can be at most as large as the grid itself. Problem source: here What would be your algorithm to solve this problem? On first thought, the naive solution should come to mind: brute-force matching. For every cell in the g...