Given a two-dimensional integer array arr of dimensions n x n, consisting solely of zeros and ones, identify the row or column (using 0-based indexing) where all elements form a palindrome. If multiple palindromes are identified, prioritize the palindromes found in rows over those in columns. Within rows or columns, the palindrome with the smaller index takes precedence. The result should be represented by the index followed by either ‘R’ or ‘C’, indicating whether the palindrome was located in a row or column. The output should be space-separated. If no palindrome is found, return the string -1.
Examples:
Input:
arr[][] = [[1, 0, 0],
[0, 1, 0],
[1, 1, 0]] Output: 1 R Explanation: In the first test case, 0-1-0 is a palindrome occuring in a row having index 1.
Input:
arr[][] = [[1, 0],
[1, 0]]
Output: 0 C
Explanation: 1-1 occurs before 0-0 in the 0th column. And there is no palindrome in the two rows.
Expected Time Complexity: O(n2)
Expected Auxiliary Space: O(1)
Constraints:
1<= arr.size <= 50
0 <= arr[i][j] <= 1
Approach 01:
-
C++
-
Python
class Solution { public: string pattern(vector<vector<int>> &arr) { int n = arr.size(); // Check for row palindrome for (int i = 0; i < n; ++i) { if (std::equal(arr[i].begin(), arr[i].end(), arr[i].rbegin())) { return std::to_string(i) + " R"; } } // Check for column palindrome for (int i = 0; i < n; ++i) { std::vector<char> col(n); for (int j = 0; j < n; ++j) { col[j] = arr[j][i]; } if (std::equal(col.begin(), col.end(), col.rbegin())) { return std::to_string(i) + " C"; } } return "-1"; } };
class Solution: def pattern(self, arr): n = len(arr) for i in range(n): if arr[i] == arr[i][::-1]: return "{} R".format(i) for i in range(n): if [arr[j][i] for j in range(n)] == [arr[j][i] for j in range(n)][::-1]: return "{} C".format(i) return "-1"