## Similar Problems

Similar Problems not available

# Find Palindrome With Fixed Length - Leetcode Solution

## Companies:

LeetCode: Find Palindrome With Fixed Length Leetcode Solution

Difficulty: Medium

Problem Statement:

You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]:

- direction can be 0 (for left shift) or 1 (for right shift).
- amount is the amount by which string s is to be shifted.

A palindrome is a word that is the same forward and backward. For example, "bob" and "racecar" are palindromes. Return true if s can become a palindrome after being shifted by each shift[i], or false otherwise.

Example 1:

Input: s = "abcde", shift = [[0,1],[1,2]] Output: false

Explanation:

- [0,1] means shift to left by 1. "abcde" -> "bcdea"
- [1,2] means shift to right by 2. "bcdea" -> "deabc"
- Palindromes cannot be effectively formed from the above sequence of shifts, thus the output is false.

Example 2:

Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]] Output: true

Explanation:

- [1,1] means shift to right by 1. "abcdefg" -> "gabcdef"
- [1,1] means shift to right by 1. "gabcdef" -> "fgabcde"
- [0,2] means shift to left by 2. "fgabcde" -> "abcdefg"
- [1,3] means shift to right by 3. "abcdefg" -> "efgabcd"
- A palindrome can be formed from the above sequence of shifts, thus the output is true.

Solution:

The first step is to apply all the given shifts to the string `s`

. We can determine the final position of each character using the following method:

- Calculate the total shift amount by subtracting the amount of right shift from the amount of left shift.
- To get the final position of each character, shift it by the total shift amount modulo the length of the string.

Once we have the shifted string, we can check if it is possible to form a palindrome from it.

A string can form a palindrome if and only if the count of each character is even, except for at most one character whose count can be odd.

We can use a hash map to count the occurrences of each character in the shifted string. If there is more than one character with an odd count, we cannot form a palindrome, and we return false. Otherwise, we can form a palindrome, and we return true.

Python Code:

```
class Solution:
def canFormPalindrome(self, s: str, shifts: List[List[int]]) -> bool:
total_shift = 0
for shift in shifts:
if shift[0] == 0:
total_shift -= shift[1]
else:
total_shift += shift[1]
n = len(s)
shifted_s = ""
for i in range(n):
shifted_s += s[(i - total_shift) % n]
count = {}
for c in shifted_s:
count[c] = count.get(c, 0) + 1
odd_count = 0
for c in count:
if count[c] % 2 != 0:
odd_count += 1
if odd_count > 1:
return False
return True
```

Time Complexity: O(N+L), where N is the length of the string `s`

and L is the number of shifts.

Space Complexity: O(N), for storing the shifted string and the character count.

## Find Palindrome With Fixed Length Solution Code

`1`