Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Find duplicate elements in an array
Next article icon

Distinct adjacent elements in an array

Last Updated : 14 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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 .
Recommended Practice
Distinct Adjacent Element
Try It!

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. 

C++
// C++ program to check if we can make // neighbors distinct. #include <bits/stdc++.h> using namespace std;  void distinctAdjacentElement(int a[], int n) {     // map used to count the frequency     // of each element occurring in the     // array     map<int, int> m;      // In this loop we count the frequency     // of element through map m .     for (int i = 0; i < n; ++i)         m[a[i]]++;      // mx store the frequency of element which     // occurs most in array .     int mx = 0;      // In this loop we calculate the maximum     // frequency and store it in variable mx.     for (int i = 0; i < n; ++i)         if (mx < m[a[i]])             mx = m[a[i]];      // By swapping we can adjust array only     // when the frequency of the element     // which occurs most is less than or     // equal to (n + 1)/2 .     if (mx > (n + 1) / 2)         cout << "NO" << endl;     else         cout << "YES" << endl; }  // Driver program to test the above function int main() {     int a[] = { 7, 7, 7, 7 };     int n = sizeof(a) / sizeof(a[0]);     distinctAdjacentElement(a, n);     return 0; } 
Python3
# Python program to check if we can make # neighbors distinct. def distantAdjacentElement(a, n):      # dict used to count the frequency     # of each element occurring in the     # array     m = dict()      # In this loop we count the frequency     # of element through map m     for i in range(n):         if a[i] in m:             m[a[i]] += 1         else:             m[a[i]] = 1      # mx store the frequency of element which     # occurs most in array .     mx = 0      # In this loop we calculate the maximum     # frequency and store it in variable mx.     for i in range(n):         if mx < m[a[i]]:             mx = m[a[i]]      # By swapping we can adjust array only     # when the frequency of the element     # which occurs most is less than or     # equal to (n + 1)/2 .     if mx > (n+1) // 2:         print("NO")     else:         print("YES")   # Driver Code if __name__ == "__main__":     a = [7, 7, 7, 7]     n = len(a)     distantAdjacentElement(a, n)  # This code is contributed by # sanjeev2552 
C#
// C# program to check if we can make  // neighbors distinct.  using System; using System.Collections.Generic;  class GFG {  public static void distinctAdjacentElement(int[] a, int n) {     // map used to count the frequency      // of each element occurring in the      // array      Dictionary<int, int> m = new Dictionary<int, int>();      // In this loop we count the frequency      // of element through map m .      for (int i = 0; i < n; ++i)     {          // checks if map already          // contains a[i] then          // update the previous         // value by incrementing          // by 1          if (m.ContainsKey(a[i]))         {             int x = m[a[i]] + 1;             m[a[i]] = x;         }         else         {             m[a[i]] = 1;         }      }      // mx store the frequency     // of element which      // occurs most in array .      int mx = 0;      // In this loop we calculate     // the maximum frequency and     // store it in variable mx.      for (int i = 0; i < n; ++i)     {         if (mx < m[a[i]])         {             mx = m[a[i]];         }     }      // By swapping we can adjust array only      // when the frequency of the element      // which occurs most is less than or      // equal to (n + 1)/2 .      if (mx > (n + 1) / 2)     {         Console.WriteLine("NO");     }     else     {         Console.WriteLine("YES");     } }      // Main Method     public static void Main(string[] args)     {         int[] a = new int[] {7, 7, 7, 7};         int n = 4;         distinctAdjacentElement(a, n);     } }  // This code is contributed // by Shrikant13 
Java
// Java program to check if we can make // neighbors distinct. import java.io.*; import java.util.HashMap; import java.util.Map; class GFG {  static void distinctAdjacentElement(int a[], int n) { // map used to count the frequency // of each element occurring in the // array HashMap<Integer,Integer> m = new HashMap<Integer, Integer>();  // In this loop we count the frequency // of element through map m . for (int i = 0; i < n; ++i){  // checks if map already contains a[i] then // update the previous value by incrementing // by 1 if(m.containsKey(a[i])){ int x = m.get(a[i]) + 1; m.put(a[i],x); } else{ m.put(a[i],1); }  }  // mx store the frequency of element which // occurs most in array . int mx = 0;  // In this loop we calculate the maximum // frequency and store it in variable mx. for (int i = 0; i < n; ++i) if (mx < m.get(a[i])) mx = m.get(a[i]);  // By swapping we can adjust array only // when the frequency of the element // which occurs most is less than or // equal to (n + 1)/2 . if (mx > (n + 1) / 2) System.out.println("NO"); else System.out.println("YES"); }  // Driver program to test the above function public static void main (String[] args) { int a[] = { 7, 7, 7, 7 }; int n = 4; distinctAdjacentElement(a, n); } } // This code is contributed by Amit Kumar 
JavaScript
<script>  // JavaScript program to check if we can make // neighbors distinct.   function distinctAdjacentElement(a, n) {     // map used to count the frequency     // of each element occurring in the     // array     let m = new Map();      // In this loop we count the frequency     // of element through map m .     for (let i = 0; i < n; ++i) {         m[a[i]]++;         if (m.has(a[i])) {             m.set(a[i], m.get(a[i]) + 1)         } else {             m.set(a[i], 1)         }     }     // mx store the frequency of element which     // occurs most in array .     let mx = 0;      // In this loop we calculate the maximum     // frequency and store it in variable mx.     for (let i = 0; i < n; ++i)         if (mx < m.get(a[i]))             mx = m.get(a[i]);      // By swapping we can adjust array only     // when the frequency of the element     // which occurs most is less than or     // equal to (n + 1)/2 .     if (mx > Math.floor((n + 1) / 2))         document.write("NO" + "<br>");     else         document.write("YES<br>"); }  // Driver program to test the above function  let a = [7, 7, 7, 7]; let n = a.length; distinctAdjacentElement(a, n);  </script> 

Output
NO

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


Next Article
Find duplicate elements in an array

S

Surya Priy
Improve
Article Tags :
  • Misc
  • DSA
  • Arrays
  • array-rearrange
Practice Tags :
  • Arrays
  • Misc

Similar Reads

  • Ways to form an array with distinct adjacent
    You are given three integers: n, m, and x (1 ≤ x ≤ m). Your task is to determine the number of valid arrays of length n that satisfy the following conditions: The first element of the array is fixed and equal to x.The last element of the array is fixed and equal to 1.For every index i from 2 to n -
    13 min read
  • Count Distinct ( Unique ) elements in an array
    Given an array arr[] of length N, The task is to count all distinct elements in arr[]. Examples:  Input: arr[] = {10, 20, 20, 10, 30, 10}Output: 3Explanation: There are three distinct elements 10, 20, and 30. Input: arr[] = {10, 20, 20, 10, 20}Output: 2 Naïve Approach: Create a count variable and ru
    15 min read
  • Count distinct elements in an array in Python
    Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
    2 min read
  • Print sorted distinct elements of array
    Given an array that might contain duplicates, print all distinct elements in sorted order. Examples: Input : 1, 3, 2, 2, 1Output : 1 2 3Input : 1, 1, 1, 2, 2, 3Output : 1 2 3The simple Solution is to sort the array first, then traverse the array and print only first occurrences of elements. Algorith
    6 min read
  • Find duplicate elements in an array
    Given an array of n integers. The task is to find all elements that have more than one occurrences. The output should only be one occurrence of a number irrespective of the number of occurrences in the input array. Examples: Input: {2, 10, 10, 100, 2, 10, 11, 2, 11, 2}Output: {2, 10, 11} Input: {5,
    11 min read
  • Print All Distinct Permutations of an Array
    Given an array arr[], Print all distinct permutations of the given array. Examples: Input: arr[] = [1, 3, 3]Output: [[1, 3, 3], [3, 1, 3], [3, 3, 1]]Explanation: Above are all distinct permutations of given array. Input: arr[] = [2, 2] Output: [[2, 2]]Explanation: Above are all distinct permutations
    6 min read
  • Count array elements whose all distinct digits appear in K
    Given an array arr[] consisting of N positive integers and a positive integer K, the task is to find the count of array elements whose distinct digits are a subset of the digits of K. Examples: Input: arr[] = { 1, 12, 1222, 13, 2 }, K = 12Output: 4Explanation: Distinct Digits of K are { 1, 2 } Disti
    15+ min read
  • Print all Distinct (Unique) Elements in given Array
    Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2} Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4
    11 min read
  • Print all distinct strings from a given array
    Given an array of strings arr[] of size N, the task is to print all the distinct strings present in the given array. Examples: Input: arr[] = { "Geeks", "For", "Geeks", "Code", "Coder" } Output: Coder Code Geeks For Explanation: Since all the strings in the array are distinct, the required output is
    5 min read
  • Product of non-repeating (distinct) elements in an Array
    Given an integer array with duplicate elements. The task is to find the product of all distinct elements in the given array. Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10}; Output : 97200 Here we take 12, 10, 9, 45, 2 for product because these are the only distinct elements Input : arr
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences