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 an element in array such that sum of left array is equal to sum of right array
Next article icon

Construct array with sum of product of same indexed elements in the given array equal to zero

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

Given an array, arr[] of size N (always even), the task is to construct a new array consisting of N non-zero integers such that the sum of the product of the same indexed elements of arr[] and the new array is equal to 0. If multiple solutions exist, print any one of them.

Examples: 

Input: arr[] = {1, 2, 3, 4}
Output: -4 -3 2 1 
Explanation: 
Sum of product of same indexed array elements of arr[] with the new array = {1 * (-4) + 2 * (-3) + 3 * (2) + 4 * (1)} = 0. 
Therefore, the required output is -4 -3 2 1.

Input: arr[] = {-1, 2, -3, 6, 4}
Output: 1 1 1 1 -1

Approach: The problem can be solved using the Greedy technique. The idea is based on the following observations:

arr[i] * (-arr[i + 1]) + arr[i + 1] * arr[i] = 0  

Follow the steps below to solve the problem:

  • Initialize an array, say newArr[] to store the new array elements such that ?(arr[i] * newArr[i]) = 0
  • Traverse the given array using variable i and check if i is even or not. If found to be true then newArr[i] = arr[i + 1].
  • Otherwise, newArr[i] = -arr[i – 1]
  • Finally, print the values of newArr[].

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 generate a new array with product
// of same indexed elements with arr[] equal to 0
void constructNewArraySumZero(int arr[], int N)
{
    // Stores sum of same indexed array
    // elements of arr and new array
    int newArr[N];
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // If i is an even number
        if (i % 2 == 0) {
 
            // Insert arr[i + 1] into
            // the new array newArr[]
            newArr[i] = arr[i + 1];
        }
 
        else {
 
            // Insert -arr[i - 1] into
            // the new array newArr[]
            newArr[i] = -arr[i - 1];
        }
    }
 
    // Print new array elements
    for (int i = 0; i < N; i++) {
        cout << newArr[i] << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, -5, -6, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    constructNewArraySumZero(arr, N);
 
    return 0;
}
 
 

Java




// Java program to implement
// the above approach
import java.util.*;
  
class GFG{
  
// Function to generate a new array with
// product of same indexed elements with
// arr[] equal to 0
static void constructNewArraySumZero(int arr[],
                                     int N)
{
     
    // Stores sum of same indexed array
    // elements of arr and new array
    int newArr[] = new int[N];
  
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // If i is an even number
        if (i % 2 == 0)
        {
             
            // Insert arr[i + 1] into
            // the new array newArr[]
            newArr[i] = arr[i + 1];
        }
        else
        {
             
            // Insert -arr[i - 1] into
            // the new array newArr[]
            newArr[i] = -arr[i - 1];
        }
    }
  
    // Print new array elements
    for(int i = 0; i < N; i++)
    {
        System.out.print(newArr[i] + " ");
    }
}
  
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3, -5, -6, 8 };
    int N = arr.length;
  
    constructNewArraySumZero(arr, N);
}
}
  
// This code is contributed by susmitakundugoaldanga
 
 

Python3




# Python3 program to implement
# the above approach
 
# Function to generate a new array
# with product of same indexed elements
# with arr[] equal to 0
def constructNewArraySumZero(arr, N):
 
    # Stores sum of same indexed array
    # elements of arr and new array
    newArr = [0] * N
 
    # Traverse the array
    for i in range(N):
         
        # If i is an even number
        if (i % 2 == 0):
 
            # Insert arr[i + 1] into
            # the new array newArr[]
            newArr[i] = arr[i + 1]
 
        else:
 
            # Insert -arr[i - 1] into
            # the new array newArr[]
            newArr[i] = -arr[i - 1]
 
    # Print new array elements
    for i in range(N):
        print(newArr[i] ,
              end = " ")
 
# Driver code
arr = [1, 2, 3, -5, -6, 8]
N = len(arr)
constructNewArraySumZero(arr, N)
 
# This code is contributed by divyeshrabadiya07
 
 

C#




// C# program to implement
// the above approach 
using System;
   
class GFG{
   
// Function to generate a new array with
// product of same indexed elements with
// arr[] equal to 0
static void constructNewArraySumZero(int[] arr,
                                     int N)
{
     
    // Stores sum of same indexed array
    // elements of arr and new array
    int[] newArr = new int[N];
   
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
          
        // If i is an even number
        if (i % 2 == 0)
        {
             
            // Insert arr[i + 1] into
            // the new array newArr[]
            newArr[i] = arr[i + 1];
        }
        else
        {
              
            // Insert -arr[i - 1] into
            // the new array newArr[]
            newArr[i] = -arr[i - 1];
        }
    }
   
    // Print new array elements
    for(int i = 0; i < N; i++)
    {
        Console.Write(newArr[i] + " ");
    }
}
   
// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 3, -5, -6, 8 };
    int N = arr.Length;
   
    constructNewArraySumZero(arr, N);
}
}
 
// This code is contributed by code_hunt
 
 

Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to generate a new array with
// product of same indexed elements with
// arr[] equal to 0
function constructNewArraySumZero(arr, N)
{
      
    // Stores sum of same indexed array
    // elements of arr and new array
    let newArr = [];
   
    // Traverse the array
    for(let i = 0; i < N; i++)
    {
          
        // If i is an even number
        if (i % 2 == 0)
        {
              
            // Insert arr[i + 1] into
            // the new array newArr[]
            newArr[i] = arr[i + 1];
        }
        else
        {
              
            // Insert -arr[i - 1] into
            // the new array newArr[]
            newArr[i] = -arr[i - 1];
        }
    }
   
    // Print new array elements
    for(let i = 0; i < N; i++)
    {
        document.write(newArr[i] + " ");
    }
}
   
    // Driver Code
    let arr = [ 1, 2, 3, -5, -6, 8 ];
    let N = arr.length;
   
    constructNewArraySumZero(arr, N);
 
// This code is contributed by souravghosh0416.
</script>
 
 
Output
2 -1 -5 -3 8 6 

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



Next Article
Find an element in array such that sum of left array is equal to sum of right array

N

nk14646
Improve
Article Tags :
  • Arrays
  • Competitive Programming
  • DSA
  • Greedy
  • Mathematical
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical

Similar Reads

  • 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
  • Count arrays of length K whose product of elements is same as that of given array
    Given an integer array arr[] of length N and an integer K, the task is to count the number of possible arrays of length K such that the product of all elements of that array is equal to the product of all elements of the given array arr[]. Since the answer can be very large, return the answer modulo
    15+ min read
  • Minimum steps to make sum and the product of all elements of array non-zero
    Given an array arr of N integers, the task is to find the minimum steps in which the sum and product of all elements of the array can be made non-zero. In one step any element of the array can be incremented by 1.Examples: Input: N = 4, arr[] = {0, 1, 2, 3} Output: 1 Explanation: As product of all e
    7 min read
  • Find an element in array such that sum of left array is equal to sum of right array
    Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sums. Examples: Input: 1 4 2 5 0Output: 2Explanation: If 2 is the partition, subarrays are : [1, 4] and [5] Input: 2 3 4 1 4 5Output: 1Explanation: If 1 is the partition, Subarrays are : [2, 3, 4] and [4
    15+ min read
  • Count of elements which is the sum of a subarray of the given Array
    Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3
    7 min read
  • Construct sum-array with sum of elements in given range
    You are given an array of n-elements and an odd-integer m. You have to construct a new sum_array from given array such that sum_array[i] = ?arr[j] for (i-(m/2)) < j (i+(m/2)). note : for 0 > j or j >= n take arr[j] = 0. Examples: Input : arr[] = {1, 2, 3, 4, 5}, m = 3 Output : sum_array = {
    7 min read
  • Print indices of array elements whose removal makes the sum of odd and even-indexed elements equal
    Given an array arr[] of size N, the task is to find indices of array elements whose removal makes the sum of odd and even indexed elements equal. If no such element exists, then print -1. Examples: Input: arr[] = {4, 1, 6, 2} Output: 1 Explanation: Removing arr[1] modifies arr[] to {4, 6, 2} Sum of
    13 min read
  • Construct Binary Array having same number of unequal elements with two other Arrays
    Given two binary arrays A[] and B[] of size N, the task is to construct the lexicographically smallest binary array X[] such that the number of non-equal elements in A and X is equal to the number of non-equal elements in B and X. If such an array does not exist return -1. Note: If there are multipl
    12 min read
  • Minimum increments to make all array elements equal with sum same as the given array after exactly one removal
    Given an array arr[] of size N and an integer K, the task is to check if all array elements can be made equal by removing an array element and incrementing the value of all other array elements such that the total sum of the array elements remains the same. If found to be true, then print "YES". Oth
    7 min read
  • Find the summation of the product of Array elements in range [L, R]
    Given an array arr[] and two integers L and R. The task is to find the sum of the product of all the pairs (i, j) in the range [L, R], such that i ≤ j. Input: arr[] = { 1, 3, 5, 8 }, L = 0, R = 2Output: 58Explanation: As 1*1 + 1*3 + 1*5 + 3*3 + 3*5 + 5*5 = 58 Input: arr[] = { 2, 1, 4, 5, 3, 2, 1 },
    8 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