# write a program to find out if there are any consecutive numbers in a given array and print sequence

### Mohammed

Guys, does anyone know the answer?

get write a program to find out if there are any consecutive numbers in a given array and print sequence from screen.

## java

For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. public class Array { public static void main(String args[]){ int a[]={10,15,1,2,3,4,5...

## Write a program to find length of longest consecutive sequence in array of integers?

Ask Question

Asked 5 years, 5 months ago

Modified 5 years, 5 months ago

Viewed 11k times 1

For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4].

public class Array {

public static void main(String args[]){

int a[]={10,15,1,2,3,4,5,11,12};

for(int i=0;iint b=1; int c=0;

if(a[i]-a[i+1]==-1){

b=b+1; c=c+1; if(b>=c) {

System.out.println(a[i]);

} else{ b=0; } } } } }

But i am getting output as 1 2 3 4 11 whereas the output should be 1 2 3 4 5.

How to get the required output,whats the mistake in a code?

javaarrayscollections

Share

edited Apr 3, 2017 at 17:13

asked Apr 3, 2017 at 17:06

Sainath Pawar 652 2 gold badges 3 3 silver badges 10 10 bronze badges 2

Have you considered sorting the array first? –

Elliott Frisch

Apr 3, 2017 at 17:07

you have to sort the array first using the Array class Array.sort(a);or you can create a for loop using bubble algorithm –

0xDEADBEEF

Apr 3, 2017 at 17:09

please, format your code. It is painful to read. –

davidxxx

Apr 3, 2017 at 17:11

@davidxxx,edited the code.Hope it is readable.Thanks for suggestion –

Sainath Pawar

Apr 3, 2017 at 17:19

Add a comment

## 5 Answers

2

You can try this out:

int[] array = {10,15,1,2,3,4,5,11,12};

List- > arrays = new ArrayList<>(); // used to store the sequences

int lastNum = array[0]; // get the fist number for compasion in loop

tempList.add(lastNum);

for (int i = 1; i < array.length; i++) {

if (array[i]-1 == lastNum) { // check for sequence (e.g fist num was 12,

// current number is 13, so 13-1 = 12,

// so it has the sequence), then store the number

tempList.add(array[i]); // store it to the temp list

lastNum = array[i]; // keep current number for the next

} else { // if it has not the sequence, start the new sequence

arrays.add(tempList); // fist store the last sequence

tempList = new ArrayList() // clear for the next sequence

lastNum = array[i]; // init the lastNumnber

tempList.add(lastNum);

} }

// now iterate for the longest array

// craete an empty array to store the longest

Listif (arr.size() > longestLength.size()) {

// check if the current array hase the longest size than the last one

// if yes, update the last one

longestLength = arr;

} }

// at the end print the result.

System.out.println("longestLength = " + longestLength);

**The Result:**

longestLength = [1, 2, 3, 4, 5]

Share

edited Apr 3, 2017 at 17:48

davidxxx 119k21 21 gold badges 195 195 silver badges 199 199 bronze badges

answered Apr 3, 2017 at 17:21

Bahramdun Adil 5,8237 7 gold badges 34 34 silver badges 63 63 bronze badges

actually i am not getting your logic –

Sainath Pawar

Apr 3, 2017 at 17:27

@SainathPawar now the logic may be clear for you! check it! –

Bahramdun Adil

Apr 3, 2017 at 17:37

1

Wrong answer. You dont have to sort the array, subsequence are found in unsorted array –

Tanuj Yadav

Apr 3, 2017 at 17:45

@SainathPawar Try to run it on {4,3,6,5,1,9,6} –

Tanuj Yadav

Apr 3, 2017 at 17:46

1

"here the sort condition optional". No the sort produces a wrong result according to the OP question. –

davidxxx

Apr 3, 2017 at 17:57

Show **3** more comments

1 Try this code

public class Array {

public static void main(String args[]){

int a[]={10,15,1,2,3,4,5,11,12};

int ms=0; // starting point of max subseq

int me=0; //ending point of max subseq

int cs=0,ce=0; //starting and ending point of current subseq

int max=0,c=0; // length of max and current subseq

for(int i=0;iif(a[i]-a[i+1]==-1){

if(c==0) //we found the first element of a subseq

{

cs=i;ce=i+1;c=2; //made the starting of currrent seq=i, end=i+1 and length=2

}

else // element is a part of subsequence but not first elem

{

ce=i+1;c++; // increased current ending point

}

if(c>max) // if lenth of current subseq is now largest then update staring and ending points of max

{ max=c; ms=cs; me=ce; } }

else // subseq ended

{ cs=0; ce=0; c=0; } }

for(i=ms;i<=me;i++) //printing max subsequence

System.out.println(a[i]);

} }

**Note: see comments for description**

Share

edited Apr 3, 2017 at 17:40

answered Apr 3, 2017 at 17:27

Tanuj Yadav 1,21113 13 silver badges 21 21 bronze badges

## Check if array elements are consecutive

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

## Check if array elements are consecutive

Difficulty Level : Easy

Last Updated : 07 Jul, 2022

Given an unsorted array of numbers, write a function that returns true if the array consists of consecutive numbers.

**Examples:**

**a)**If the array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5.

**b)**If the array is {83, 78, 80, 81, 79, 82}, then the function should return true because the array has consecutive numbers from 78 to 83.

**c)**If the array is {34, 23, 52, 12, 3}, then the function should return false because the elements are not consecutive.

**d)**If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive.

Recommended Problem

Consecutive Array Elements

Arrays Solve Problem

Submission count: 2.7K

**Method 1 (Use Sorting)**

1) Sort all the elements.

2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.

## C++

#includeusing namespace std;

// Function to Check if array

// elements are consecutive

bool areConsecutive(int arr[], int n)

{ //Sort the array sort(arr,arr+n);

// checking the adjacent elements

for(int i=1;i{

if(arr[i]!=arr[i-1]+1)

{ return false; } } return true; }

/* Driver program to test above functions */

int main() {

int arr[]= {5, 4, 2, 3, 1, 6};

int n = sizeof(arr)/sizeof(arr[0]);

if(areConsecutive(arr, n) == true)

cout<<" Array elements are consecutive ";

else

cout<<" Array elements are not consecutive ";

return 0; }

// This code is contributed by Aarti_Rathi

## Java

## Python

## C#

Java Python C# Javascript

**Output**

Array elements are consecutive

**Time Complexity:**O(n log n)

**Space Complexity:**O(1)

**Method 2 (Use visited array)**

The idea is to check for the following two conditions. If the following two conditions are true, then return true.

1) where max is the maximum element in the array, min is the minimum element in the array and n is the number of elements in the array.

2) All elements are distinct.

To check if all elements are distinct, we can create a visited[] array of size n. We can map the ith element of input array arr[] to the visited array by using arr[i] – min as the index in visited[].

## C++

#include#include/* Helper functions to get minimum and maximum in an array */

int getMin(int arr[], int n);

int getMax(int arr[], int n);

/* The function checks if the array elements are consecutive

If elements are consecutive, then returns true, else returns

false */

bool areConsecutive(int arr[], int n)

{ if ( n < 1 ) return false;

/* 1) Get the minimum element in array */

int min = getMin(arr, n);

/* 2) Get the maximum element in array */

int max = getMax(arr, n);

/* 3) max - min + 1 is equal to n, then only check all elements */

if (max - min + 1 == n)

{

/* Create a temp array to hold visited flag of all elements.

Note that, calloc is used here so that all values are initialized

as false */

bool *visited = (bool *) calloc (n, sizeof(bool));

int i;

for (i = 0; i < n; i++)

{

/* If we see an element again, then return false */

if ( visited[arr[i] - min] != false )

return false;

/* If visited first time, then mark the element as visited */

visited[arr[i] - min] = true;

}

/* If all elements occur once, then return true */

return true; }

return false; // if (max - min + 1 != n)

}

/* UTILITY FUNCTIONS */

int getMin(int arr[], int n)

{ int min = arr[0];

for (int i = 1; i < n; i++)

if (arr[i] < min) min = arr[i]; return min; }

int getMax(int arr[], int n)

{ int max = arr[0];

for (int i = 1; i < n; i++)

if (arr[i] > max) max = arr[i]; return max; }

/* Driver program to test above functions */

int main() {

int arr[]= {5, 4, 2, 3, 1, 6};

int n = sizeof(arr)/sizeof(arr[0]);

if(areConsecutive(arr, n) == true)

printf(" Array elements are consecutive ");

else

printf(" Array elements are not consecutive ");

getchar(); return 0; }

## Java

## Python3

## C#

## PHP

Java Python3 C# PHP Javascript

**Output**

Array elements are consecutive

**Time Complexity:**O(n)

**Auxiliary Space:**O(n)

**Method 3 (Mark visited array elements as negative)**

This method is O(n) time complexity and O(1) extra space, but it changes the original array, and it works only if all numbers are positive. We can get the original array by adding an extra step though. It is an extension of method 2, and it has the same two steps.

1) where max is the maximum element in the array, min is the minimum element in the array and n is the number of elements in the array.

## Check if Array Elements are Consecutive

If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs.

## Check if Array Elements are Consecutive

Table of Contents [hide]

Problem Solution

Program to check if Array Elements are Consecutive

Was this post helpful?

If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs.

In this post, we will see how to check if array elements are consecutive.

## Problem

Given an array, we need to check if array contains consecutive elements.

For example:

Input: array[] = {5, 3, 4, 1, 2}

Output: true

As array contains consecutive elements from 1 to 5

Input: array[] = {47, 43, 45, 44, 46}

Output: true

As array contains consecutive elements from 43 to 47

Input: array[] = {6, 7, 5, 6}

Output: false

As array does not contain consecutive elements.

## Solution

Simple solution will be to sort the array and check if elements are consecutive just by iterative over array but time complexity of this solution will be o(n^logn).

**Can we do better?**

Yes, we can do better

Find minimum and maximum element in the array.

Check if **max-min+1==n**, if elements are consecutive then this condition should meet.

Create a visited boolean array.

Iterate over the array and check

visited[arr[i]-min] is true, then return false as elements are repeated.

mark the element visited.

### Program to check if Array Elements are Consecutive

MaximumOccurringCharacterMain.java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

package org.arpit.java2blog;

public class ArrayConsecutiveElementMain{

/* Method return minimum value*/

private int getMinimum(int arr[], int n)

{ int min = arr[0];

for (int i = 1; i < n; i++)

if (arr[i] < min) min = arr[i]; return min; }

/* Method return maximum value*/

private int getMaximum(int arr[], int n)

{ int max = arr[0];

for (int i = 1; i < n; i++)

if (arr[i] > max) max = arr[i]; return max; }

/* This method checks if array elements are consecutive */

public boolean checkArrayContainsConsecutiveElements(int arr[], int n)

{ if ( n < 1 ) return false;

int min = getMinimum(arr, n);

int max = getMaximum(arr, n);

if (max - min + 1 == n)

{

boolean[] visited=new boolean[arr.length];

for (int i = 0; i < n; i++)

{

if ( visited[arr[i] - min] != false )

return false;

visited[arr[i] - min] = true;

} return true; } return false; }

public static void main(String args[])

{

ArrayConsecutiveElementMain acem=new ArrayConsecutiveElementMain();

int arr[]= {47, 43, 45, 44, 46};

if(acem.checkArrayContainsConsecutiveElements(arr, arr.length))

System.out.println(" Array elements are consecutive ");

else

System.out.println(" Array elements are not consecutive ");

return; } }

When you run above program, you will get below output:

Array elements are consecutive

Time complexity of this solution is o(n).

That’s all about how to check if Array Elements are Consecutive.

### Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

import_contacts

### You may also like:

Search for a range Leetcode – Find first and last position of element in sorted array

Sort an array of 0s, 1s and 2s

Check if it is possible to reach end of given Array by Jumping

Find the local minima in array

Sliding Window Maximum in java

Count number of occurrences (or frequency) of each element in a sorted array

Find subarrays with given sum in an array.

Count 1’s in sorted Binary Array

Find peak element in the array

Find first repeating element in an array of integers

‹ 1 2 3 4 ›

Guys, does anyone know the answer?