VOOZH about

URL: https://www.geeksforgeeks.org/dsa/distinct-adjacent-elements-array/

⇱ Distinct adjacent elements in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Distinct adjacent elements in an array

Last Updated : 14 Jul, 2022

Given an array, find whether it is possible to obtain an array having distinct neighbouring elements by swapping two neighbouring array elements.

Examples: 

Input : 1 1 2
Output : YES
swap 1 (second last element) and 2 (last element), 
to obtain 1 2 1, which has distinct neighbouring 
elements .

Input : 7 7 7 7
Output : NO
We can't swap to obtain distinct elements in 
neighbor .

To obtain an array having distinct neighbouring elements is possible only, when the frequency of most occurring element is less than or equal to half of size of array i.e ( <= (n+1)/2 ). To make it more clear consider different examples 

1st Example : 
 a[] = {1, 1, 2, 3, 1} 
 We can obtain array {1, 2, 1, 3, 1} by 
 swapping (2nd and 3rd) element from array a. 
 Here 1 occurs most and its frequency is 
 3 . So that 3 <= ((5+1)/2) .
 Hence, it is possible. 

Below is the implementation of this approach. 


Output
NO

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

Comment
Article Tags: