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
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Count subarrays having sum of elements at even and odd positions equal
Next article icon

Generate an N-length array having equal count and sum of elements of both parities

Last Updated : 28 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer N (3 ≤ N ≤ 105), the task is to generate an array of N distinct positive elements such that the count and sum of elements of both parties i.e even and odd, are the same. If it is not possible to construct such an array, print -1.

Examples:

Input: N = 8 
Output: 2, 4, 6, 8, 1, 3, 5, 11

Input: 6 
Output: -1 
Explanation: For the count of odd and even array elements to be equal, 3 even and odd elements must be present in the array. But, sum of 3 odd elements will always be odd. Therefore, it is not possible to generate such an array.

 

Approach: Follow the steps below to solve the problem:

  1. If N is odd or (N / 2) is odd, then print -1.
  2. Otherwise: 
    • Print N/2 even values starting from 2 and store the count in some variable, say SumEven.
    • Print N / 2 - 1 odd values starting from 1 and store the sum in another variable, say SumOdd.
    • At last print SumEven - SumOdd which is also odd.

Below is the implementation of the above approach:

C++
// C++ Program to implement // the above approach  #include <bits/stdc++.h> using namespace std;  // Function to print the // required sequence void Print(int N) {     if ((N / 2) % 2 == 1  || (N % 2 == 1)) {         cout << -1 << endl;         return;     }  // Stores count of even // and odd elements     int CurEven = 2, CurOdd = 1;  // Stores sum of even // and odd elements     int SumOdd = 0, SumEven = 0;  // Print N / 2 even elements     for (int i = 0; i < (N / 2); i++) {          cout << CurEven << " ";         SumEven += CurEven;         CurEven += 2;     }  // Print N / 2 - 1 odd elements     for (int i = 0; i < N / 2 - 1; i++) {         cout << CurOdd << " ";         SumOdd += CurOdd;         CurOdd += 2;     }      CurOdd = SumEven - SumOdd;      // Print final odd element     cout << CurOdd << '\n'; }  // Driver Code int main() {     int N = 12;     Print(N);     return 0; } 
Java
// Java Program to implement // the above approach import java.io.*; class GFG  {    // Function to print the   // required sequence   static void Print(int N)   {     if ((N / 2) % 2 == 1 || (N % 2 == 1))      {       System.out.print(-1);       return;     }      // Stores count of even     // and odd elements     int CurEven = 2, CurOdd = 1;      // Stores sum of even     // and odd elements     int SumOdd = 0, SumEven = 0;      // Print N / 2 even elements     for (int i = 0; i < (N / 2); i++)      {       System.out.print(CurEven + " ");       SumEven += CurEven;       CurEven += 2;     }      // Print N / 2 - 1 odd elements     for (int i = 0; i < N / 2 - 1; i++)     {       System.out.print(CurOdd + " ");       SumOdd += CurOdd;       CurOdd += 2;     }     CurOdd = SumEven - SumOdd;      // Print final odd element     System.out.println(CurOdd);   }    // Driver Code   public static void main (String[] args)    {     int N = 12;     Print(N);   } }  // This code is contributed by Dharanendra L V. 
Python3
# Python Program to implement # the above approach  # Function to print the # required sequence def Print(N):     if ((N / 2) % 2 or (N % 2)):         print(-1)         return  # Stores count of even # and odd elements     CurEven = 2     CurOdd = 1  # Stores sum of even # and odd elements     SumOdd = 0     SumEven = 0  # Print N / 2 even elements     for i in range(N // 2):          print(CurEven,end=" ")         SumEven += CurEven         CurEven += 2  # Print N / 2 - 1 odd elements     for i in range( (N//2) - 1):         print(CurOdd, end=" ")         SumOdd += CurOdd         CurOdd += 2      CurOdd = SumEven - SumOdd      # Print final odd element     print(CurOdd)  # Driver Code N = 12 Print(N)  # This code is contributed by rohitsingh07052 
C#
// C# Program to implement // the above approach using System; class GFG  {    // Function to print the   // required sequence   static void Print(int N)   {     if ((N / 2) % 2 == 1 || (N % 2 == 1))      {       Console.WriteLine(-1);       return;     }      // Stores count of even     // and odd elements     int CurEven = 2, CurOdd = 1;      // Stores sum of even     // and odd elements     int SumOdd = 0, SumEven = 0;      // Print N / 2 even elements     for (int i = 0; i < (N / 2); i++)      {       Console.Write(CurEven + " ");       SumEven += CurEven;       CurEven += 2;     }      // Print N / 2 - 1 odd elements     for (int i = 0; i < N / 2 - 1; i++)     {       Console.Write(CurOdd + " ");       SumOdd += CurOdd;       CurOdd += 2;     }     CurOdd = SumEven - SumOdd;      // Print final odd element     Console.WriteLine(CurOdd);   }    // Driver Code   public static void Main()   {     int N = 12;     Print(N);   } }  // This code is contributed by chitranayal. 
JavaScript
<script>  // Javascript Program to implement // the above approach  // Function to print the // required sequence function Print(N) {     if ((N / 2) % 2 == 1 || (N % 2 == 1))      {          document.write(-1);         return;     }          // Stores count of even     // and odd elements     var CurEven = 2, CurOdd = 1;          // Stores sum of even     // and odd elements     var SumOdd = 0, SumEven = 0;          // Print N / 2 even elements     for(var i = 0; i < (N / 2); i++)      {         document.write(CurEven + " ");         SumEven += CurEven;         CurEven += 2;     }          // Print N / 2 - 1 odd elements     for(var i = 0; i < N / 2 - 1; i++)     {         document.write(CurOdd + " ");         SumOdd += CurOdd;         CurOdd += 2;     }     CurOdd = SumEven - SumOdd;          // Print final odd element     document.write(CurOdd); }  // Driver Code var N = 12;  Print(N);  // This code is contributed by Ankita saini  </script> 

Output: 
2 4 6 8 10 12 1 3 5 7 9 17

 

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


Next Article
Count subarrays having sum of elements at even and odd positions equal

V

varuntak22
Improve
Article Tags :
  • Misc
  • Greedy
  • Mathematical
  • DSA
Practice Tags :
  • Greedy
  • Mathematical
  • Misc

Similar Reads

  • Count N-length arrays of made up of elements not exceeding 2^K - 1 having maximum sum and Bitwise AND equal to 0
    Given two integers N and K, the task is to find the number of N-length arrays that satisfies the following conditions: The sum of the array elements is maximum possible.For every possible value of i ( 1 ? i ? N ), the ith element should lie between 0 and 2K - 1.Also, Bitwise AND of all the array ele
    7 min read
  • Count subarrays having sum of elements at even and odd positions equal
    Given an array arr[] of integers, the task is to find the total count of subarrays such that the sum of elements at even position and sum of elements at the odd positions are equal. Examples: Input: arr[] = {1, 2, 3, 4, 1}Output: 1Explanation: {3, 4, 1} is the only subarray in which sum of elements
    7 min read
  • Generate an array having sum of Bitwise OR of same-indexed elements with given array equal to K
    Given an array arr[] consisting of N integers and an integer K, the task is to print an array generated such that the sum of Bitwise OR of same indexed elements of the generated array with the given array is equal to K. If it is not possible to generate such an array, then print "-1". Examples: Inpu
    7 min read
  • Find the array element having equal count of Prime Numbers on its left and right
    Given an array arr[] consisting of N positive integers, the task is to find an index from the array having count of prime numbers present on its left and right are equal. Examples: Input: arr[] = {2, 3, 4, 7, 5, 10, 1, 8}Output: 2Explanation: Consider the index 2, then the prime numbers to its left
    13 min read
  • Split an Array A[] into Subsets having equal Sum and sizes equal to elements of Array B[]
    Given an array A[] consisting of N integers, the task is to split the array A[] into subsets having equal sum and of length equal to elements in array B[]. Examples: Input: A[] = {17, 13, 21, 20, 50, 29}, B[] = {2, 3, 1} Output: 21 29 17 13 20 50 Input: A[] = { 1, 2, 3, 4, 5, 6}, B[] = { 2, 2, 2} Ou
    8 min read
  • Count pairs in an array having sum of elements with their respective sum of digits equal
    Given an array arr[] consisting of N positive integers, the task is to count the number of pairs in the array, say (a, b) such that sum of a with its sum of digits is equal to sum of b with its sum of digits. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Following are the pairs that sati
    8 min read
  • Count of pairs having each element equal to index of the other from an Array
    Given an integer N and an array arr[] that contains elements in the range [1, N], the task is to find the count of all pairs (arr[i], arr[j]) such that i < j and i == arr[j] and j == arr[i]. Examples: Input: N = 4, arr[] = {2, 1, 4, 3} Output: 2 Explanation: All possible pairs are {1, 2} and {3,
    6 min read
  • Count of index pairs with equal elements in an array | Set 2
    Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i != j Examples: Input: arr[]={1, 2, 1, 1}Output: 3 Explanation:In the array arr[0]=arr[2]=arr[3]Valid Pairs are (0, 2), (0, 3) and (2, 3) Input: arr[]={2, 2, 3, 2, 3}Output: 4Ex
    8 min read
  • Count pairs in given Array having sum of index and value at that index equal
    Given an array arr[] containing positive integers, count the total number of pairs for which arr[i]+i = arr[j]+j such that 0≤i<j≤n-1. Examples: Input: arr[] = { 6, 1, 4, 3 }Output: 3Explanation: The elements at index 0, 2, 3 has same value of a[i]+i as all sum to 6 {(6+0), (4+2), (3+3)}. Input: a
    8 min read
  • Sum of elements from an array having even parity
    Given an array arr[], the task is to calculate the sum of the elements from the given array which has even parity i.e. the number of set bits is even using bitwise operator. Examples: Input: arr[] = {2, 4, 3, 5, 9} Output: 17 Only 3(0011), 5(0101) and 9(1001) have even parity So 3 + 5 + 9 = 17 Input
    6 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