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:
Generate minimum sum sequence of integers with even elements greater
Next article icon

Generate sequence with equal sum of adjacent integers

Last Updated : 19 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer N, find a sequence of N integers such that the sum of all integers in the sequence is equal to the sum of any two adjacent integers in the sequence.

Examples:

Input: N = 4
Output: 1 -1 1 -1
Explanation: Total sum of the four integers is 0 and the sum of any two adjacent integers is also 0.

Input: N = 5
Output: 1 -2 1 -2 1
Explanation: Total sum of the four integers is -1 and the sum of any two adjacent integers is also -1.

Approach: To solve the problem follow the below idea:

  • For even n, we can use the array [-1, 1, -1, 1, ..., -1, 1] as a solution. This array has a length of n, and the sum of any two adjacent elements is 0, as well as the sum of the whole array.
  • For odd n, we can construct an array s of length n using two fixed values a and b, such that si-1 = si+1  for i = 2, 3, ...n-1. Specifically, we can set s1 = a and s2 = b, and then create the array s = [a, b, a, b, ..., a, b, a]. We can then solve for 'a' and 'b' using the fact that the sum of any two adjacent elements and the sum of the whole array must be equal.
  • If we let k be a positive integer such that n = 2k+1, then we can find values for 'a' and 'b' that satisfy the conditions. Specifically, we can set a = k-1 and b = -k, which produces the array [k-1, -k, k-1, -k, ..., k-1, -k, k-1]. This array has a length of n, and the sum of any two adjacent elements is k-1-k = -1, as well as the sum of the whole array being k(k-1)-(k-1)k = 0.
  • However, there is no solution for n = 3, as a = 0 and b = 0 do not satisfy the conditions. In general, the array we constructed will not work if a or b is equal to 0. Therefore, we must have k ≥ 2 to ensure that both a and b are nonzero.
  • Overall, this approach shows that if there is a solution for even n, then there is a solution for odd n greater than or equal to 5.

Follow the steps to solve the problem:

  • Initialize an integer variable 'num' with the value N/2.
  • If N is even print 1, -1, ........., 1, -1
  • If N is odd :
    • iterate through the sequence of integers from 1 to N.
    • If i is odd, print -num, otherwise print num-1.

Below is the implementation for the above approach:

C++
// C++ code for the above approach: #include <bits/stdc++.h> using namespace std;  // Function to solve the problem void solve(int n) {      // If n is odd     if (n % 2) {          // Calculate the number to be         // added and subtracted         // alternatively         int num = n / 2;          // Iterate through the sequence         // and print the values         for (int i = 0; i < n; i++) {             if (i % 2)                  // If i is odd, print                 // the negative number                 cout << -num << " ";              // Otherwise, print the             // positive number             else                 cout << num - 1 << " ";         }          // Print a newline character         // at the end         cout << endl;     }      // If n is even     else {          // Iterate through the sequence         // and print the values         for (int i = 0; i < n; i++) {              // If i is odd, print -1             if (i % 2)                 cout << -1 << " ";              // Otherwise, print 1             else                 cout << 1 << " ";         }          // Print a newline character         // at the end         cout << endl;     } }  // Driver function int main() {     int n = 9;      // Call the solve function with n = 9     solve(9); } 
Java
// JAVA code for the above approach:  public class GFG {     // Function to solve the problem     public static void solve(int n) {         // If n is odd         if (n % 2 == 1) {             // Calculate the number to be added and             // subtracted alternatively             int num = n / 2;              // Iterate through the sequence and print the values             for (int i = 0; i < n; i++) {                 if (i % 2 == 1)                     // If i is odd, print the negative number                     System.out.print(-num + " ");                 else                     // Otherwise, print the positive number                     System.out.print(num - 1 + " ");             }             // Print a newline character at the end             System.out.println();         }         // If n is even         else {             // Iterate through the sequence and print the values             for (int i = 0; i < n; i++) {                 // If i is odd, print -1                 if (i % 2 == 1)                     System.out.print(-1 + " ");                 // Otherwise, print 1                 else                     System.out.print(1 + " ");             }             // Print a newline character at the end             System.out.println();         }     }      // Driver function     public static void main(String[] args) {         int n = 9;          // Call the solve function with n = 9         solve(9);     } }   // this code is contributed by rambabuguphka 
Python3
def solve(n):     # If n is odd     if n % 2:         # Calculate the number to be added and subtracted alternatively         num = n // 2          # Iterate through the sequence and print the values         for i in range(n):             if i % 2:                 # If i is odd, print the negative number                 print(-num, end=" ")             else:                 # Otherwise, print the positive number                 print(num - 1, end=" ")          # Print a newline character at the end         print()      # If n is even     else:         # Iterate through the sequence and print the values         for i in range(n):             # If i is odd, print -1             if i % 2:                 print(-1, end=" ")             # Otherwise, print 1             else:                 print(1, end=" ")          # Print a newline character at the end         print()   # Driver function if __name__ == "__main__":     n = 9      # Call the solve function with n = 9     solve(9)  # This code is contributed by shivamgupta310570 
C#
using System;  public class GFG {     // Function to solve the problem     static void Solve(int n)     {         // If n is odd         if (n % 2 != 0)         {             // Calculate the number to be             // added and subtracted             // alternatively             int num = n / 2;              // Iterate through the sequence             // and print the values             for (int i = 0; i < n; i++)             {                 if (i % 2 != 0)                      // If i is odd, print                     // the negative number                     Console.Write(-num + " ");                  // Otherwise, print the                 // positive number                 else                     Console.Write(num - 1 + " ");             }              // Print a newline character             // at the end             Console.WriteLine();         }          // If n is even         else         {             // Iterate through the sequence             // and print the values             for (int i = 0; i < n; i++)             {                 // If i is odd, print -1                 if (i % 2 != 0)                     Console.Write(-1 + " ");                  // Otherwise, print 1                 else                     Console.Write(1 + " ");             }              // Print a newline character             // at the end             Console.WriteLine();         }     }      // Driver function     public static void Main(string[] args)     {         int n = 9;          // Call the solve function with n = 9         Solve(n);     } }  // This code is contributed by akshitaguprzj3 
JavaScript
// Function to solve the problem function solve(n) {      // If n is odd     if (n % 2) {              // Calculate the number to be         // added and subtracted         // alternatively         let num = Math.floor(n / 2);                  // Iterate through the sequence         // and print the values         for (let i = 0; i < n; i++) {             if (i % 2)                 // If i is odd, print                 // the negative number                 console.log(-num + " ");                          // Otherwise, print the             // positive number             else                 console.log(num - 1 + " ");         }                  // Print a newline character         // at the end         console.log();     }          // If n is even     else {              // Iterate through the sequence         // and print the values         for (let i = 0; i < n; i++) {                      // If i is odd, print -1             if (i % 2)                 console.log(-1 + " ");                              // Otherwise, print 1             else                 console.log(1 + " ");         }                  // Print a newline character         // at the end         console.log();     } }  // Driver function let n = 9; solve(9); 

Output
3 -4 3 -4 3 -4 3 -4 3  

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


Next Article
Generate minimum sum sequence of integers with even elements greater

R

rohityadavcdece19
Improve
Article Tags :
  • Mathematical
  • DSA
Practice Tags :
  • Mathematical

Similar Reads

  • Generate minimum sum sequence of integers with even elements greater
    Given an integer N, the task is to generate a sequence of N positive integers such that: Every element at the even position must be greater than the element succeeding it and the element preceding it i.e. arr[i - 1] < arr[i] > arr[i + 1]The sum of the elements must be even and the minimum poss
    5 min read
  • Count of ways to generate Sequence of distinct consecutive odd integers with sum N
    Given an integer N, the task is to find the total number of ways a sequence can be formed consisting of distinct consecutive odd integers that add up to N. Examples: Input: N = 45Output: 3Explanation: 3 ways to choose distinct consecutive odd numbers that add up to 45 are - {5, 7, 9, 11, 13}, {13, 1
    6 min read
  • Number of Subsequences with Even and Odd Sum
    Given an array, find the number of subsequences whose sum is even and the number of subsequences whose sum is odd. Example: Input: arr[] = {1, 2, 2, 3} Output: EvenSum = 7, OddSum = 8 There are [Tex]2^{N}-1 [/Tex]possible subsequences. The subsequences with even sum is 1) {1, 3} Sum = 4 2) {1, 2, 2,
    15 min read
  • Generate longest Array containing distinct even integers with sum N
    Given an integer N. Find the maximum length sequence containing distinct even integers with sum N. In case, such a sequence does not exist, return an empty sequence. Examples: Input: N = 12Output : {2, 6, 4}Explanation: 2, 6 and 4 are even and 2+6+4=12. Note that {4, 8} sequence also contains even n
    8 min read
  • Print all non-increasing sequences of sum equal to a given number x
    Given a number x, print all possible non-increasing sequences with sum equals to x. Examples: Input: x = 3 Output: 1 1 1 2 1 3 Input: x = 4 Output: 1 1 1 1 2 1 1 2 2 3 1 4 We strongly recommend you to minimize your browser and try this yourself first.The idea is to use a recursive function, an array
    9 min read
  • Count total number of even sum sequences
    Given an integer N, the task is to count all possible sequences of length N such that all the elements of the sequence are from the range [1, N] and the sum of the elements of the sequence is even. As the answer could be very large so print the answer modulo 109 + 7.Examples: Input: N = 3 Output: 13
    12 min read
  • Count of adjacent pairs in given Array with even sum
    Given an array arr[] of N integers, the task is to find the count of pairs of adjacent elements whose sum is even where each element can belong to at most one pair. Example: Input: arr[] = {1, 12, 1, 3, 5}Output: 1Explanation: 1 pair can be formed with arr[3] and arr[4]. Input: arr[] = {1, 2, 3, 4,
    4 min read
  • Smallest Integer to be inserted to have equal sums
    Given an array of positive integers, find the smallest non-negative integer (i.e. greater than or equal to zero) that can be placed between any two elements of the array such that the sum of elements in the subarray occurring before it is equal to the sum of elements occurring in the subarray after
    8 min read
  • Number of Subsequences with Even and Odd Sum | Set 2
    Given an array arr[] of size N. The task is to find the number of subsequences whose sum is even and the number of subsequences whose sum is odd.Examples: Input: arr[] = {1, 2, 2, 3} Output: EvenSum = 7, OddSum = 8 There are 2N-1 possible subsequences. The subsequences with even sum are 1) {1, 3} Su
    7 min read
  • Find all combinations of two equal sum subsequences
    Given an array arr[] of integers, the task is to find all possible ways the array could be split into two subsequences such that the sum of the elements in both the subsequences is equal. Each number in the array must belong to only one of the two subsequences. Print all possible combinations of two
    11 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