VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-orientation-of-a-pattern-in-a-matrix/

⇱ Find orientation of a pattern in a matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find orientation of a pattern in a matrix

Last Updated : 23 Jul, 2025

Given a matrix of characters and a pattern, find the orientation of pattern in the matrix. In other words, find if pattern appears in matrix in horizontal or vertical direction. Achieve this in minimum time possible.

Input:
mat[N][N] = { {'a', 'b', 'c', 'd', 'e'},
 {'f', 'g', 'h', 'i', 'j'},
 {'k', 'l', 'm', 'n', 'o'},
 {'p', 'q', 'r', 's', 't'},
 {'u', 'v', 'w', 'x', 'y'}};
pattern = "pqrs";

Output: Horizontal

We strongly recommend you to minimize your browser and try this yourself first.
A simple solution is for each row and column, use Naive pattern searching algorithm to find the orientation of pattern in the matrix. The time complexity of Naive pattern searching algorithm for every row is O(NM) where N is size of the matrix and M is length of the pattern. So, the time complexity of this solution will be O(N*(NM)) as each of N rows and N columns takes O(NM) time.

Can we do better? 
The idea is to use KMP pattern matching algorithm for each row and column. The KMP matching algorithm improves the worst case to O(N + M). The total cost of a KMP search is linear in the number of characters of string and pattern. For a N x N matrix and pattern of length M, complexity of this solution will be O(N*(N+M)) as each of N rows and N columns will take O(N + M) time. 

Implementation:


Output
Horizontal

Time complexity: O(n2).
Auxiliary Space: O(m)

Comment
Article Tags:
Article Tags: