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:
Sort elements of an array A[] placed on a number line by shifting i-th element to (i + B[i])th positions minimum number of times
Next article icon

Minimum elements inserted in a sorted array to form an Arithmetic progression

Last Updated : 17 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sorted array arr[], the task is to find minimum elements needed to be inserted in the array such that array forms an Arithmetic Progression.
Examples: 
 

Input: arr[] = {1, 6, 8, 10, 14, 16} 
Output: 10 
Explanation: 
Minimum elements required to form A.P. is 10. 
Transformed array after insertion of the elements. 
arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 
9, 10, 11, 12, 13, 14, 15, 16} 
Input: arr[] = {1, 3, 5, 7, 11} 
Output: 1 
Explanation: 
Minimum elements required to form A.P. is 1. 
Transformed array after insertion of the elements. 
arr[] = {1, 3, 5, 7, 9, 11} 
 

 

Approach: The idea is to find the difference of consecutive elements of the sorted array and then find the greatest common divisor of all the differences. The GCD of the differences will be the common-difference for the arithmetic progression that can be formed. Below is the illustration of the steps:
 

  • Find the difference between consecutive elements of the array and store in it diff[].
  • Now the GCD of the diff[] array will give the common difference between the elements of given sorted array. 
    For Example: 
     
Given array be {1, 5, 7} Difference of Consecutive elements will be - Difference(1, 5) = |5 - 1| = 4 Difference(5, 7) = |7 - 5| = 2  Then, GCD of the Differences will be  gcd(4, 2) = 2  This means there can be A.P. formed with common-difference as 2. That is -  {1, 3, 5, 7}
  •  
  • If the difference between consecutive elements of the sorted array arr[] is greater than the GCD calculated above, then the minimum number of elements needed to be inserted in the given array to make the element of the array in Arithmetic Progression is given by: 
     
Number of possible elements =      (Difference / Common Difference) - 1
  •  
  • Add the count of element needed to be insert for all set of consecutive elements in the given sorted array.

Below is the implementation of the above approach:
 

C++




// C++ implementation to find the
// minimum elements required to
// be inserted into an array to
// form an arithmetic progression
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the greatest
// common divisor of two numbers
int gcdFunc(int a, int b)
{
    if (b == 0)
        return a;
    return gcdFunc(b, a % b);
}
 
// Function to find the minimum
// the minimum number of elements
// required to be inserted into array
int findMinimumElements(int* a, int n)
{
    int b[n - 1];
     
    // Difference array of consecutive
    // elements of the array
    for (int i = 1; i < n; i++) {
        b[i - 1] = a[i] - a[i - 1];
    }
    int gcd = b[0];
     
    // GCD of the difference array
    for (int i = 0; i < n - 1; i++) {
        gcd = gcdFunc(gcd, b[i]);
    }
    int ans = 0;
     
    // Loop to calculate the minimum
    // number of elements required
    for (int i = 0; i < n - 1; i++) {
        ans += (b[i] / gcd) - 1;
    }
    return ans;
}
 
// Driver Code
int main()
{
    int arr1[] = { 1, 6, 8, 10, 14, 16 };
    int n1 = sizeof(arr1)/sizeof(arr1[0]);
    // Function calling
    cout << findMinimumElements(arr1, n1)
         << endl;
}
 
 

Java




// Java implementation to find the
// minimum elements required to
// be inserted into an array to
// form an arithmetic progression
  
class GFG{
  
    // Function to find the greatest
    // common divisor of two numbers
    static int gcdFunc(int a, int b)
    {
        if (b == 0)
            return a;
        return gcdFunc(b, a % b);
    }
      
    // Function to find the minimum
    // the minimum number of elements
    // required to be inserted into array
    static int findMinimumElements(int[] a, int n)
    {
        int[] b = new int[n - 1];
          
        // Difference array of consecutive
        // elements of the array
        for (int i = 1; i < n; i++) {
            b[i - 1] = a[i] - a[i - 1];
        }
        int gcd = b[0];
          
        // GCD of the difference array
        for (int i = 0; i < n - 1; i++) {
            gcd = gcdFunc(gcd, b[i]);
        }
        int ans = 0;
          
        // Loop to calculate the minimum
        // number of elements required
        for (int i = 0; i < n - 1; i++) {
            ans += (b[i] / gcd) - 1;
        }
        return ans;
    }
      
 // Driver Code
public static void main(String[] args)
{
    int arr1[] = { 1, 6, 8, 10, 14, 16 };
    int n1 = arr1.length;
    // Function calling
    System.out.print(findMinimumElements(arr1, n1)
         +"\n");
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 implementation to find the
# minimum elements required to
# be inserted into an array to
# form an arithmetic progression
 
# Function to find the greatest
# common divisor of two numbers
def gcdFunc(a, b):
    if (b == 0):
        return a
     
    return gcdFunc(b, a % b)
 
# Function to find the minimum
# the minimum number of elements
# required to be inserted into array
def findMinimumElements(a, n):
    b = [0]*(n - 1)
     
    # Difference array of consecutive
    # elements of the array
    for i in range(1,n):
        b[i - 1] = a[i] - a[i - 1]
         
    gcd = b[0]
 
    # GCD of the difference array
    for i in range(n-1):
        gcd = gcdFunc(gcd, b[i])
     
    ans = 0
     
    # Loop to calculate the minimum
    # number of elements required
    for i in range(n-1):
        ans += (b[i] // gcd) - 1
     
    return ans
 
# Driver Code
arr1 = [1, 6, 8, 10, 14, 16]
n1 = len(arr1)
# Function calling
print(findMinimumElements(arr1, n1))
 
# This code is contributed by shubhamsingh10
 
 

C#




// C# implementation to find the
// minimum elements required to
// be inserted into an array to
// form an arithmetic progression
using System;
 
class GFG{
 
    // Function to find the greatest
    // common divisor of two numbers
    static int gcdFunc(int a, int b)
    {
        if (b == 0)
            return a;
        return gcdFunc(b, a % b);
    }
     
    // Function to find the minimum
    // the minimum number of elements
    // required to be inserted into array
    static int findMinimumElements(int[] a, int n)
    {
        int[] b = new int[n - 1];
         
        // Difference array of consecutive
        // elements of the array
        for (int i = 1; i < n; i++) {
            b[i - 1] = a[i] - a[i - 1];
        }
        int gcd = b[0];
         
        // GCD of the difference array
        for (int i = 0; i < n - 1; i++) {
            gcd = gcdFunc(gcd, b[i]);
        }
        int ans = 0;
         
        // Loop to calculate the minimum
        // number of elements required
        for (int i = 0; i < n - 1; i++) {
            ans += (b[i] / gcd) - 1;
        }
        return ans;
    }
     
    // Driver Code
    static public void Main ()
    {
        int[] arr1 = new int[] { 1, 6, 8, 10, 14, 16 };
        int n1 = arr1.Length;
        // Function calling
        Console.WriteLine(findMinimumElements(arr1, n1));
    }
}
 
// This code is contributed by shivanisingh
 
 

Javascript




<script>
 
// Javascript implementation to find the
// minimum elements required to
// be inserted into an array to
// form an arithmetic progression
 
 
// Function to find the greatest
// common divisor of two numbers
function gcdFunc(a, b)
{
    if (b == 0)
        return a;
    return gcdFunc(b, a % b);
}
 
// Function to find the minimum
// the minimum number of elements
// required to be inserted into array
function findMinimumElements(a, n)
{
    let b = new Array(n - 1);
     
    // Difference array of consecutive
    // elements of the array
    for (let i = 1; i < n; i++) {
        b[i - 1] = a[i] - a[i - 1];
    }
    let gcd = b[0];
     
    // GCD of the difference array
    for (let i = 0; i < n - 1; i++) {
        gcd = gcdFunc(gcd, b[i]);
    }
    let ans = 0;
     
    // Loop to calculate the minimum
    // number of elements required
    for (let i = 0; i < n - 1; i++) {
        ans += (b[i] / gcd) - 1;
    }
    return ans;
}
 
// Driver Code
 
    let arr1 = [ 1, 6, 8, 10, 14, 16 ];
    let n1 = arr1.length;
    // Function calling
    document.write(findMinimumElements(arr1, n1)
        + "<br>");
 
// This code is contributed by Mayank Tyagi
 
</script>
 
 
Output: 
10

 

Time Complexity: O(N * log(MAX)), where N is the number of elements in the array and MAX is the maximum element in the array.
Auxiliary Space: O(N + log(MAX)) 



Next Article
Sort elements of an array A[] placed on a number line by shifting i-th element to (i + B[i])th positions minimum number of times

A

AmanGupta65
Improve
Article Tags :
  • Algorithms
  • Analysis of Algorithms
  • Arrays
  • C++ Programs
  • Data Structures
  • DSA
  • arithmetic progression
Practice Tags :
  • Algorithms
  • Arrays
  • Data Structures

Similar Reads

  • Sum of minimum elements of all possible sub-arrays of an array
    Given an array arr[], the task is to find the sum of the minimum elements of every possible sub-array of the array. Examples: Input: arr[] = {1, 3, 2} Output: 15 All possible sub-arrays are {1}, {2}, {3}, {1, 3}, {3, 2} and {1, 3, 2} And, the sum of all the minimum elements is 1 + 2 + 3 + 1 + 2 + 1
    9 min read
  • C++ Program to Print all triplets in sorted array that form AP
    Given a sorted array of distinct positive integers, print all triplets that form AP (or Arithmetic Progression)Examples :   Input : arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 }; Output : 6 9 12 2 12 22 12 17 22 2 17 32 12 22 32 9 22 35 2 22 42 22 32 42 Input : arr[] = { 3, 5, 6, 7, 8, 10, 12}; Ou
    4 min read
  • Minimize insertions in an array to obtain all sums upto N
    Given a sorted array arr[] of positive integers of size K, and an integer N. The task is to find the minimum number of elements to be inserted in this array, such that all positive integers in range [1, N] can be obtained as a sum of subsets of the modified array. Note: The array won't have any dupl
    10 min read
  • Minimum possible sum of array elements after performing the given operation
    Given an array arr[] of positive integers and an integer x, the task is to minimize the sum of elements of the array after performing the given operation at most once. In a single operation, any element from the array can be divided by x (if it is divisible by x) and at the same time, any other elem
    8 min read
  • Sort elements of an array A[] placed on a number line by shifting i-th element to (i + B[i])th positions minimum number of times
    Given two arrays A[] and B[] consisting of N positive integers such that each array element A[i] is placed at the ith position on the number line, the task is to find the minimum number of operations required to sort the array elements arranged in the number line. In each operation any array element
    9 min read
  • C++ Program for Minimum product pair an array of positive Integers
    Given an array of positive integers. We are required to write a program to print the minimum product of any two numbers of the given array.Examples: Input : 11 8 5 7 5 100 Output : 25 Explanation : The minimum product of any two numbers will be 5 * 5 = 25. Input : 198 76 544 123 154 675 Output : 744
    3 min read
  • Minimum count of numbers required from given array to represent S
    Given an integer S and an array arr[], the task is to find the minimum number of elements whose sum is S, such that any element of the array can be chosen any number of times to get sum S. Examples: Input: arr[] = {25, 10, 5}, S = 30 Output: 2 Explanation: In the given array there are many possible
    15+ min read
  • Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum
    Given an array arr[] of some positive integers and missing occurrence of a specific integer represented by -1, the task is to find that missing number such that maximum absolute difference between adjacent elements is minimum.Examples: Input: arr[] = {-1, 10, -1, 12, -1} Output: 11 Explanation: Diff
    6 min read
  • Minimum MEX from all subarrays of length K
    Given an array arr[] consisting of N distinct positive integers and an integer K, the task is to find the minimum MEX from all subarrays of length K. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {1, 2, 3}, K = 2Output: 1Explanation:All subarrays
    7 min read
  • Partitioning into two contiguous element subarrays with equal sums
    Given an array of n positive integers. Find a minimum positive element to be added to one of the indexes in the array such that it can be partitioned into two contiguous sub-arrays of equal sums. Output the minimum element to be added and the position where it is to be added. If multiple positions a
    10 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