×

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements.

Example: 

Input: a [ ] = {2 , 4 , 6 ,10 , 12 , 14 }

Output: 8

Explanation

The above sequence is in Arithmetic Progression with difference 2. We can find the missing element by traversing through the sequence. 8 is missing in the above sequence.

Method 1:Using Mathematical Formula

Finding the missing number by linearly navigating the array is a Simple Solution. This solution's time complexity is O (n).

According to mathematical formulas, the sum of the n elements in an AP is equal to (n/2)(a+l).

The number of components is n, and the first and last elements are a and l, respectively.

If we use this formula and maintain the results in a variable called s, we can add up all the components and keep the result in total. By using s-sum, we will find the missing number.

Program to find the missing number in given sequence in Java

MissingNumberAP.java

import java . io . * ;
class MissingNumberAP {
static int Missing ( int[] arr , int n )
{
int first , last , s , i , sum = 0 , number ;
first = arr [ 0 ] ;
last = arr [ n - 1 ] ;
if ( ( first + last ) % 2 == 0 ) 
{
s = ( first + last ) / 2 ;
s = s * ( n + 1 ) ;
}
else {
s = ( n + 1 ) / 2 ;
s = ( first + last ) * s ;
}
for ( i = 0 ; i <= n - 1 ; i++ ) {
sum = sum + arr [ i ] ;
}
number = s – sum ;
return number ;
}
public static void main ( String [ ] args  )
{
int  a[] = { 2 , 4 , 6 , 10 , 12 , 14 } ;
int l = a . length ;
System . out . println(" Missing element in the sequence is "+ Missing ( a, l ) ) ;
}
}

Output:

Missing Number in an Arithmetic Progression in Java

Let’s see another approach for the same.

Binary Search can also be used to address this issue in O(Logn) time. The goal is to reach the middle component. In order to determine whether the missing piece is between middle and middle+1, determine whether the difference between middle and next to middle equals diff or not. The missing element is in the right half if the middle element is equal to the n/2th term in the Arithmetic Series. Other component is in the left half.

MissingNumberAP2.java

import java.io.*; 
class MissingNumberAP2
{
static int findMissing(int arr[], int l, int h, int diff)
{
if ( h <= l )
return Integer . MAX_VALUE ;
int mid = l + ( h - l ) / 2 ;
if ( arr [ mid + 1] - arr [ mid ] != diff )
return ( arr [ mid ] + diff ) ;
if ( mid > 0 && arr [ mid ] - arr [ mid - 1 ] != diff )
return ( arr [ mid - 1 ] + diff ) ;
if ( arr [ mid ] == arr [ 0 ] + mid * diff )
return findMissing ( arr , mid + 1 , h , diff ) ;
return findMissing ( arr , l , mid - 1 , diff ) ;
}
static int Missing ( int a [ ] , int n)
{
int d = (a [ n - 1 ] - a [ 0 ] ) / n ;
return findMissing(a, 0, n - 1, d ) ;
}
public static void main (String[] args)
{
int a [ ] = {2 , 4 , 6 , 8 , 12 , 14 } ;
int l = a . length ;
System . out . println ("The missing element is "+ Missing ( a, l ) ) ;
}
}

Output:

Missing Number in an Arithmetic Progression in Java

Let’s see the efficient approach.

The goal is to reach the central component. If the middle element's index is equal to 1, the missing element is located in the right half; otherwise, it is located in the left half. The missing element will be located between high and low after breaking free of the binary search cycle. By combining a common difference with an element at index high or a common difference with an element at index low, we can identify the missing element.

MissingNumberAP3.java

import java . io . * ;
class MissingNumberAP3
{
// static method declaration
static int Missing(int arr [ ] , int l ,int h , int diff )
{
int mid ;
while ( l <= h )
{
mid = ( l + h ) / 2 ;
if ((arr[mid] - arr[0]) / diff == mid)
l = mid + 1;
else
h = mid - 1;
}
return arr[h] + diff;
}
static int Missing(int a [ ] , int n)
{

int d = (a [n - 1] - a [ 0 ] ) / n ;


return Missing ( a , 0 , n - 1 , d ) ;
}


// Main method where execution of the program starts
public static void main (String[] args)
{
int a [ ] = { 2 , 4 , 6 , 10 , 12 , 14 } ;
int l = a . length;
System . out . println ( " The missing element is " + Missing ( a , l ) ) ;
}
}

Output

Missing Number in an Arithmetic Progression in Java

Related Topics

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

How to Convert String to enum in Java?

In this article, we shall gain the complete knowledge about how to convert the string to enum in Java. The complete process that happens in the approach shall be discussed...

3 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.