# The Grid Search – HackerRank Solution

In this post, we will solve The Grid Search HackerRank Solution. This problem (The Grid Search) is a part of HackerRak Problem Solving series.

Contents

Given an array of strings of digits, try to find the occurrence of a given pattern of digits. In the grid and pattern arrays, each string represents a row in the grid. For example, consider the following grid:

1234567890
0987654321
1111111111
1111111111
2222222222

The pattern array is:

876543
111111
111111

The pattern begins at the second row and the third column of the grid and continues in the following two rows. The pattern is said to be present in the grid. The return value should be YES or NO, depending on whether the pattern is found. In this case, return YES.

Function Description

Complete the gridSearch function in the editor below. It should return YES if the pattern exists in the grid, or NO otherwise.

gridSearch has the following parameter(s):

• string G[R]:Â the grid to search
• string P[r]:Â the pattern to search for

## Input Format

The first line contains an integerÂ t, the number of test cases.

Each of theÂ tÂ test cases is represented as follows:
The first line contains two space-separated integersÂ RÂ andÂ C, the number of rows in the search gridÂ GÂ and the length of each row string.
This is followed byÂ RÂ lines, each with a string ofÂ CÂ digits that represent the gridÂ G.
The following line contains two space-separated integers,Â rÂ andÂ c, the number of rows in the pattern gridÂ PÂ and the length of each pattern row string.
This is followed byÂ rÂ lines, each with a string ofÂ cÂ digits that represent the pattern gridÂ P.

Returns

• string:Â eitherÂ YESÂ orÂ NO

## Constraints

• 1 <= t <= 5
• 1 <= R, r, C, c <= 1000
• 1 <= r <= R
• 1 <= c <= C

Sample Input

2
10 10
7283455864
6731158619
8988242643
3830589324
2229505813
5633845374
6473530293
7053106601
0834282956
4607924137
3 4
9505
3845
3530
15 15
400453592126560
114213133098692
474386082879648
522356951189169
887109450487496
252802633388782
502771484966748
075975207693780
511799789562806
404007454272504
549043809916080
962410809534811
445893523733475
768705303214174
650629270887160
2 2
99
99

Sample Output

YES
NO

Explanation

The first test in the input file is:

10 10
7283455864
6731158619
8988242643
3830589324
2229505813
5633845374
6473530293
7053106601
0834282956
4607924137
3 4
9505
3845
3530

The pattern is present in the larger grid as marked in bold below.

7283455864
6731158619
8988242643
3830589324
2229505813
5633845374
6473530293
7053106601
0834282956
4607924137

The second test in the input file is:

15 15
400453592126560
114213133098692
474386082879648
522356951189169
887109450487496
252802633388782
502771484966748
075975207693780
511799789562806
404007454272504
549043809916080
962410809534811
445893523733475
768705303214174
650629270887160
2 2
99
99

The search pattern is:

99
99

## Solution – The Grid Search – HackerRank Solution

### C++

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main(){
int t;
cin >> t;
for(int a0 = 0; a0 < t; a0++){
int R;
int C;
cin >> R >> C;
vector<string> G(R);
for(int G_i = 0;G_i < R;G_i++){
cin >> G[G_i];
}
int r;
int c;
cin >> r >> c;
vector<string> P(r);
for(int P_i = 0;P_i < r;P_i++){
cin >> P[P_i];
}
// Optimization - continue if P > G
if(r > R || c > C) {
cout<<"NO\n";
continue;
}
bool patternExists = false;
// Main algorithm
for(int i = 0; i < R; i++) {
bool foundMatch = false;
for(int j = 0; j < C; j++) {
if(G[i][j] == P[0][0] && (i+r <= R) && (j+c <= C)) {
// Potential match
bool match = true;
for(int x = 0; x < r; x++) {
bool rowMatch = true;
for(int y = 0; y < c; y++) {
if(P[x][y] != G[x+i][y+j]) {
rowMatch = false;
match = false;
break;
}
}
if(!rowMatch) {
break;
}
}
if(match) {
foundMatch = true;
break;
}
}
}
if(foundMatch) {
patternExists = true;
break;
}
}
if(patternExists) {
cout<<"YES\n";
} else {
cout<<"NO\n";
}
}
return 0;
}

### Python

import sys
import re

def occurrences(string, sub):
res = []
ind = 0
while ind < len(string) - len(sub) + 1:
found = string.find(sub, ind)
#print("ind = {} found = {}".format(ind, found))
if found != -1:
res.append(found)
ind = found + 1
else:
break
return res

def gridSearch(G, P):
for ind_g in range(len(G) - len(P) + 1):
cur = -1
all_occurrences = []
for ind_p, s_pat in enumerate(P):
all_occurrences.append(occurrences(G[ind_g + ind_p], s_pat))
#ret = G[ind_g + ind_p].find(s_pat)
#print("ind_g = {} ind_p = {} check {} in {}".format(ind_g, ind_p, s_pat, G[ind_g + ind_p]))

#if ret == -1 or (ind_p > 0 and cur != ret):
#    break
#elif ind_p == len(P) - 1:
#    return 'YES'
#else:
#    cur = ret

#print(all_occurrences)
ourset = set(all_occurrences[0])
for lst in all_occurrences:
ourset &= set(lst)

#print("ourset = {}".format(ourset))
if len(ourset) >= 1:
return 'YES'

return 'NO'

if __name__ == "__main__":
t = int(input().strip())
for a0 in range(t):
R, C = input().strip().split(' ')
R, C = [int(R), int(C)]
G = []
G_i = 0
for G_i in range(R):
G_t = str(input().strip())
G.append(G_t)
r, c = input().strip().split(' ')
r, c = [int(r), int(c)]
P = []
P_i = 0
for P_i in range(r):
P_t = str(input().strip())
P.append(P_t)
result = gridSearch(G, P)
print(result)

### Java

import java.io.*;
import java.util.*;

public class Solution {

public static boolean isMatch(String[] grid, int r, int c, String[] pattern) {
for(int i = r; i < r + pattern.length; i++) {
if(!grid[i].substring(c, c + pattern[0].length()).equals(pattern[i - r]))
return false;
}
return true;
}

public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your clas should be named Solution. */
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int k = 0; k < T; k++){
int R = sc.nextInt();
int C = sc.nextInt();
String[] grid = new String[R];
for(int i = 0; i < R; i++){
grid[i] = sc.next();
}
int r = sc.nextInt();
int c = sc.nextInt();
String[] pattern = new String[r];
for(int i = 0; i < r; i++) {
pattern[i] = sc.next();
}
boolean ret = false;
for(int i = 0; i <= R - r; i++){
for(int j = 0; j <= C - c; j++){
if(grid[i].charAt(j) == pattern[0].charAt(0)){
ret = isMatch(grid, i, j, pattern);
if(ret)
break;
}
}
if(ret)
break;
}
if(ret){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}

Note: This problem (The Grid Search) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.