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:
Generate a unique Array of length N with sum of all subarrays divisible by N
Next article icon

Generate an Array such that the sum of any Subarray is not divisible by its Length

Last Updated : 10 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer N. Then the task is to output an array let's say A[] of length N such that:

  • The sum S, of any subarray, let's say A[L, R] where (L != R) must not leave the remainder as 0 when dividing by the length of A[L, R]. Formally, Sum(A[L, R])%(length of A[L, R]) != 0.
  • A[] must contain all unique elements.

Note: Subarrays must be chosen at least of length equal to 2.

Examples:

Input: N = 3

Output: A[] = {7, 2, 5}

Explanation: There can be three possible subarrays of length at least equal to 2:

  • A[1, 2]: The length and sum of subarray is 2 and (7+2) = 9 respectively. We can see that (9%2) != 0
  • A[2, 3]: The length and sum of subarray is 2 and (2+5) = 7 respectively. We can see that (7%2) != 0
  • A[1, 3]: The length and sum of subarray is 3 and (7+2+5) = 14 respectively. We can see that (14%3) != 0

There is no subarray such that its sum is perfectly divisible by its length. A[] also contains N distinct elements. Therefore, output array A[] is valid.

Input: N = 2

Output: A[] = {2, 1}

Explanation: It can be verified that both conditions are followed by the output array A[].

Approach: Implement the idea below to solve the problem

The problem is observation based and can be solved using those observations. Let us see some observations:

  • When N is an even number, we can output a permutation.
  • When n is an odd number, we can replace N with N + 1 and again we get another array consisting of N distinct integers.
  • Examples:
    • N = 7, A[] = {2, 1, 4, 3, 6, 5, 8}
    • N = 8, A[] = {2, 1, 4, 3, 6, 5, 8, 7}

General formula:

  • N is Odd: A[] = {2, 1, 3, 4, ... N-1, N-2, N+1}
  • N is Even: A[] = {2, 1, 3, 4, ... N, N-1}

Steps were taken to solve the problem:

  • If (N is Odd)
    • Output {2, 1, 3, 4, ... N-1, N-2, N+1} using loop.
  • If (N is Even)
    • Output {2, 1, 3, 4, ... N, N-1} using loop.

Code to implement the approach:

C++
#include <iostream>  void GFG(int N) {     // Check if N is odd or even     if (N % 2 == 1) {         // Print elements for the odd N         for (int i = 1; i < N; i += 2)             std::cout << i + 1 << " " << i << " ";         std::cout << N + 1 << std::endl;     } else {         // Print elements for even N         for (int i = 1; i <= N; i += 2)             std::cout << i + 1 << " " << i << " ";     } } int main() {     // Input     int N = 8;     // Function call     GFG(N);     return 0; } 
Java
// Java code to implement the approach  // Driver Class public class Main {      // Driver Function     public static void main(String[] args)     {         // Input         int N = 8;          // Function call         Print_array(N);     }      // Method to print A[]     public static void Print_array(int N)     {         if (N % 2 == 1) {             for (int i = 1; i < N; i += 2)                 System.out.print(i + 1 + " " + i + " ");             System.out.println(N + 1);         }         else {             for (int i = 1; i <= N; i += 2)                 System.out.print(i + 1 + " " + i + " ");         }     } } 
Python3
# Python code to implement the approach  # Method to print A[] def Print_array(N):     if N % 2 == 1:         for i in range(1, N, 2):             print(i + 1, i, end=" ")         print(N + 1)     else:         for i in range(1, N+1, 2):             print(i + 1, i, end=" ")  # Driver function def main():     # Input     N = 8      # Function call     Print_array(N)  if __name__ == '__main__':     main()  # This code is contributed by ragul21 
C#
using System;  class GFG {     static void Main(string[] args)     {         // Input         int N = 8;         // Function call         PrintArray(N);     }      // Method to print elements based on N     static void PrintArray(int N)     {         // Check if N is odd or even         if (N % 2 == 1)         {             // Print elements for the odd N             for (int i = 1; i < N; i += 2)                 Console.Write(i + 1 + " " + i + " ");             Console.WriteLine(N + 1);         }         else         {             // Print elements for even N             for (int i = 1; i <= N; i += 2)                 Console.Write(i + 1 + " " + i + " ");         }     } } 
JavaScript
function GFG(N) {      // Check if N is odd or even      if (N % 2 === 1) {          // Print elements for the odd N          for (let i = 1; i < N; i += 2)              console.log(i + 1, i);          console.log(N + 1);      } else {          // Print elements for even N          for (let i = 1; i <= N; i += 2)              console.log(i + 1, i);      }  }  // Input  let N = 8;  // Function call  GFG(N); 

Output
2 1 4 3 6 5 8 7 

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


Next Article
Generate a unique Array of length N with sum of all subarrays divisible by N
author
pradeep6036ymca
Improve
Article Tags :
  • Geeks Premier League
  • DSA
  • Arrays
  • Arrays
  • Geeks Premier League 2023
Practice Tags :
  • Arrays
  • Arrays

Similar Reads

  • Generate a unique Array of length N with sum of all subarrays divisible by N
    Given an integer N, the task is to make an array of unique elements of length N such that all subarrays sum modulo N equals to zero. Examples: Input: N = 6 Output: 6 12 18 24 30 36 Explanation: Since all elements are a multiple of 6. Hence all subarrays add up to a sum divisible by 6.Input: N = 4 Ou
    3 min read
  • Generate an N-length array having sum of each subarray divisible by K
    Given two positive integers N and K, the task is to generate an array consisting of N distinct integers such that the sum of elements of each subarray of the constructed array is divisible by K. Examples: Input: N = 3, K = 3Output: 3 6 9Explanation:The subarrays of the resultant array are {3}, {6},
    4 min read
  • Generate an array with product of all subarrays of length exceeding one divisible by K
    Given two positive integers N and K, the task is to generate an array of length N such that the product of every subarray of length greater than 1 must be divisible by K and the maximum element of the array must be less than K. If no such array is possible, then print -1. Examples: Input: N = 3, K =
    6 min read
  • Find a subarray whose sum is divisible by size of the array
    Given an array arr[] of length N. The task is to check if there exists any subarray whose sum is a multiple of N. If there exists such subarray, then print the starting and ending index of that subarray else print -1. If there are multiple such subarrays, print any of them. Examples: Input: arr[] =
    13 min read
  • Max sum of Subarray of length N/2 where sum is divisible by N
    Given an array, arr[] of size N where N is even, the task is to find the maximum possible sum of the subarray of length N/2 where the sum is divisible by N. Examples: Input: arr[] = {2, 3, 4, 5, 6, 7}, N = 6Output:18Explanation: Here, N = 6, The maximum possible sum of a sublist of length 3 (N/2) is
    8 min read
  • Count ways to split an array into subarrays such that sum of the i-th subarray is divisible by i
    Given an array arr[] consisting of N integers, the task is to find the number of ways to split the array into non-empty subarrays such that the sum of the ith subarray is divisible by i. Examples: Input: arr[] = {1, 2, 3, 4}Output: 3Explanation:Following are the number of ways to split the array int
    8 min read
  • Generate a sequence with product N such that for every pair of indices (i, j) and i < j, arr[j] is divisible by arr[i]
    Given a positive integer N, the task is to generate a sequence say arr[] of maximum length having all elements at least 2 such that the product of all the numbers in the sequence is N and for any pair of indices (i, j) and i < j, arr[j] is divisible by arr[i]. Examples: Input: N = 360Output: Maxi
    11 min read
  • Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N
    Given an array of N integers, the task is to find a non-empty subset such that the sum of elements of the subset is divisible by N. Output any such subset with its size and the indices(1-based indexing) of elements in the original array if it exists. Prerequisites: Pigeonhole PrincipleExamples: Inpu
    8 min read
  • Build Array of length N such that exactly X Subarrays have positive sums
    Given integers N and X, the task is to construct an array of size N such that exactly X subarrays have positive sums and other subarrays have negative sums. Note: If multiple subarrays are possible, print any of them. Examples: Input: N = 3, X = 2Output: 2 -1 -2Explanation: [0, 0] and [0, 1] subarra
    9 min read
  • Sum of all the elements in an array divisible by a given number K
    Given an array containing N elements and a number K. The task is to find the sum of all such elements which are divisible by K. Examples: Input : arr[] = {15, 16, 10, 9, 6, 7, 17} K = 3 Output : 30 Explanation: As 15, 9, 6 are divisible by 3. So, sum of elements divisible by K = 15 + 9 + 6 = 30. Inp
    13 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