VOOZH about

URL: https://www.geeksforgeeks.org/dsa/constructing-palindromic-arrays-with-first-element-as-x/

⇱ Constructing Palindromic Arrays with First Element as X - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Constructing Palindromic Arrays with First Element as X

Last Updated : 12 Feb, 2024

Given two integers N and X (1 <= X <= N). The task is to find a permutation P of [1,2,3...N] with the first element as X, such that the difference array Diff[], where Diffi = P(i+1) - Pi for all i (1 <= i < N), forms a palindrome. If no such permutation exists, output -1.

Examples:

Input: N = 4, X = 3
Output: P[] = {3, 1, 4, 2}
Explanation: If P[] = {3, 1, 4, 2}, Then:

  • First element of P[] is equal to X = 3, which is true.
  • Calculating Diff[] for all i (1 <= i < N) gives = {(P2-P1), (P3-P2), (P4-P3)} = {(1-3), (4-1), (2-4)} = {-2, 3, -2}, which is palindrome.

Thus, P[] follows all the conditions, having length N and all elements are from the range [1, N].

Input: N = 3, X = 2
Output: -1
Explanation: It can be verified that no such P[] exists for the given values of N and X.


Approach:

The problem is observation based. The main idea is:

  • If N is odd and X is equal to (N + 1)/2, then no such P[] exists.
  • Otherwise, a possible permutation P[] will always be there. Which can be obtained by following below sequence:
    • First, we have to print the X.
    • Then print all numbers from 1 to N except X and (N - X + 1).
    • Finally print (N - X + 1).

Step-by-step approach:

  • Check Special Case:
    • If N is odd and X is equal to (N + 1) / 2, output -1.
  • Generate Permutation:
    • Calculate Y = N - X + 1.
    • Print X.
    • Print all numbers from 1 to N except X and Y.
    • Print Y.

Below is the implementation of the above approach:


Output
4 2 3 1 

Time Complexity: O(N)
Auxiliary space: O(1)

Comment
Article Tags: