VOOZH about

URL: https://www.geeksforgeeks.org/dsa/adjacent-element-arrangement-in-circular-array/

⇱ Adjacent element arrangement in Circular Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Adjacent element arrangement in Circular Array

Last Updated : 29 Nov, 2023

Given a circular array arr[] of size N where the last element is adjacent to the first element, the task is to arrange an array where the adjacent element's absolute difference is 1. Return "YES" Otherwise "NO".

Examples:

Input: N = 6, arr[] = {1, 1, 2, 2, 2, 3}
Output: YES
Explanation: {2, 1, 2, 1, 2, 3} is one of the possible rearrangements.

Approach: This can be solved with the following idea:

Check the parity of each element, and store them in different vectors. Check whether the absolute difference between even and odd elements is 1 or not.

Below are the steps involved:

  • Initialize two vectors even and odd.
  • Store even elements in even and odd in odd vectors.
  • If the size of both vectors is different, Return "NO".
  • Check for each odd [i] - even [i], the difference is one or not, for each i.
  • Return "YES", if 1 for everyone.

Below is the implementation of the code:


Output
YES

Time Complexity: O(N)
Auxilairy Space: O(N)

Comment