×

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

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.