Created
April 11, 2024 09:45
-
-
Save kunal768/9c94898684af06deb9acd2333f47f4d3 to your computer and use it in GitHub Desktop.
Sub palindrome queries - HackerEarth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Question Link - https://www.hackerearth.com/practice/algorithms/string-algorithm/string-searching/practice-problems/algorithm/palindrome-queries-eefd5c23/ | |
''' | |
Problem | |
You are given a string | |
that contains | |
lowercase alphabets. There are | |
queries of the form | |
. Your task is to determine if every character in the range | |
can be arranged in such a manner that a palindromic substring for that range can be formed. If it is possible to create the palindrome substring in the provided interval, then print Possible. Otherwise, print Impossible. | |
Note: The original string is not changed in the process. | |
Input format | |
First line: | |
denotes the number of queries | |
Second lines: String | |
of | |
lowercase English letters | |
Third line: Number of queries of the | |
format | |
Output format | |
lines for each query. Print Possible if a palindrome substring is formed in the provided interval. Otherwise, print Impossible. | |
Constraints | |
Sample Input | |
4 | |
abccab | |
1 3 | |
2 3 | |
3 3 | |
3 5 | |
Sample Output | |
Impossible | |
Impossible | |
Possible | |
Possible | |
''' | |
# Concept : Create Prefix sum over string for all letters | |
# Now in L to R, get count of each alphabet using PF[R] - PF[L-1] | |
# If in a string the number of chars with odd count are greater than 1 then we cant make it a palindrome | |
q = int(input()) | |
s = input() | |
n = len(s) | |
D = { chr(i+97) : [0]*n for i in range(26)} | |
vis = set() | |
for i, val in enumerate(s): | |
if not val in vis : | |
vis.add(val) | |
arr = D[val] | |
for x in range(n): | |
if s[x] == val: | |
arr[x] += 1 | |
for x in range(1, n): | |
arr[x] += arr[x - 1] | |
D[val] = arr | |
for _ in range(q) : | |
l, r = map(int, input().split()) | |
l, r = l - 1, r - 1 | |
odd_cnt = 0 | |
for k in D : | |
if (D[k][r] - D[k][l-1]) %2 != 0 : | |
odd_cnt += 1 | |
if odd_cnt > 1 : | |
print("Impossible") | |
else: | |
print("Possible") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment