Check if array contains contiguous integers with duplicates allowed - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship
Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise
Must Do Questions
DSA Topic-wise
DSA Company-wise
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Geek on the Top
Careers
Internship
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Events




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Practice DS & Algo.
                        


Must Do Questions

DSA Topic-wise

DSA Company-wise


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Geek on the Top

Careers

Internship


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Practice DS & Algo.
                        


Must Do Questions

DSA Topic-wise

DSA Company-wise


Must Do Questions


DSA Topic-wise


DSA Company-wise


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Geek on the Top

Careers

Internship


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Geek on the Top


Careers


Internship


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Check if array contains contiguous integers with duplicates allowed
Check if array elements are consecutive | Added Method 4
Find the smallest missing number
Maximum sum such that no two elements are adjacent | Set 2
Maximum sum such that no two elements are adjacent
Find maximum possible stolen value from houses
Find number of solutions of a linear equation of n variables
Count number of ways to reach a given score in a game
Program for Fibonacci numbers
Program for nth Catalan Number
Bell Numbers (Number of ways to Partition a Set)
Binomial Coefficient | DP-9
Permutation Coefficient
Tiling Problem
Gold Mine Problem
Coin Change | DP-7
Find minimum number of coins that make a given value
Greedy Algorithm to find Minimum number of Coins
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Minimum Number of Platforms Required for a Railway/Bus Station
Reverse an array in groups of given size
K’th Smallest/Largest Element in Unsorted Array | Set 1
K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)
K’th Smallest/Largest Element using STL
Arrays in Java
Write a program to reverse an array or string
Largest Sum Contiguous Subarray
Program for array rotation
Arrays in C/C++
Check if array contains contiguous integers with duplicates allowed
Check if array elements are consecutive | Added Method 4
Find the smallest missing number
Maximum sum such that no two elements are adjacent | Set 2
Maximum sum such that no two elements are adjacent
Find maximum possible stolen value from houses
Find number of solutions of a linear equation of n variables
Count number of ways to reach a given score in a game
Program for Fibonacci numbers
Program for nth Catalan Number
Bell Numbers (Number of ways to Partition a Set)
Binomial Coefficient | DP-9
Permutation Coefficient
Tiling Problem
Gold Mine Problem
Coin Change | DP-7
Find minimum number of coins that make a given value
Greedy Algorithm to find Minimum number of Coins
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Minimum Number of Platforms Required for a Railway/Bus Station
Reverse an array in groups of given size
K’th Smallest/Largest Element in Unsorted Array | Set 1
K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)
K’th Smallest/Largest Element using STL
Arrays in Java
Write a program to reverse an array or string
Largest Sum Contiguous Subarray
Program for array rotation
Arrays in C/C++
Difficulty Level :
Easy
Given an array of n integers(duplicates allowed). Print “Yes” if it is a set of contiguous integers else print “No”.
Examples:  
Input : arr[] = {5, 2, 3, 6, 4, 4, 6, 6}
Output : Yes
The elements form a contiguous set of integers
which is {2, 3, 4, 5, 6}.

Input : arr[] = {10, 14, 10, 12, 12, 13, 15}
Output : No
We have discussed different solutions for distinct elements in the below post. Check if array elements are consecutiveA simple solution is to first sort the array. Then traverse the array to check if all consecutive elements differ at most by one.  
C
Java
Python3
C#
PHP
Javascript
// Sorting based C++ implementation// to check whether the array// contains a set of contiguous// integers#include <bits/stdc++.h>using namespace std; // function to check whether// the array contains a set// of contiguous integersbool areElementsContiguous(int arr[], int n){    // Sort the array    sort(arr, arr+n);          // After sorting, check if     // current element is either     // same as previous or is     // one more.    for (int i = 1; i < n; i++)        if (arr[i] - arr[i-1] > 1)            return false;         return true;} // Driver program to test aboveint main(){    int arr[] = { 5, 2, 3, 6,                     4, 4, 6, 6 };    int n = sizeof(arr) / sizeof(arr[0]);         if (areElementsContiguous(arr, n))        cout << "Yes";         else        cout << "No";         return 0;}
// Sorting based Java implementation// to check whether the array// contains a set of contiguous// integersimport java.util.*; class GFG {         // function to check whether    // the array contains a set    // of contiguous integers    static boolean areElementsContiguous(int arr[],                                             int n)    {       // Sort the array       Arrays.sort(arr);             // After sorting, check if       // current element is either       // same as previous or is       // one more.       for (int i = 1; i < n; i++)         if (arr[i] - arr[i-1] > 1)              return false;             return true;       }         /* Driver program to test above function */    public static void main(String[] args)    {        int arr[] = { 5, 2, 3, 6,                      4, 4, 6, 6 };        int n = arr.length;                 if (areElementsContiguous(arr, n))            System.out.println("Yes");                 else            System.out.println("No");              }     }     // This code is contributed by Arnav Kr. Mandal.   
# Sorting based Python implementation# to check whether the array# contains a set of contiguous integers def areElementsContiguous(arr, n):    # Sort the array    arr.sort()         # After sorting, check if    # current element is either    # same as previous or is    # one more.    for i in range(1,n):        if (arr[i] - arr[i-1] > 1) :            return 0    return 1 # Driver codearr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]n = len(arr)if areElementsContiguous(arr, n): print("Yes")else: print("No") # This code is contributed by 'Ansu Kumari'.
// Sorting based C# implementation// to check whether the array// contains a set of contiguous// integersusing System; class GFG {         // function to check whether    // the array contains a set    // of contiguous integers    static bool areElementsContiguous(int []arr,                                            int n)    {    // Sort the array    Array.Sort(arr);         // After sorting, check if    // current element is either    // same as previous or is    // one more.    for (int i = 1; i < n; i++)        if (arr[i] - arr[i - 1] > 1)            return false;         return true;    }         // Driver program    public static void Main()    {        int []arr = { 5, 2, 3, 6,                    4, 4, 6, 6 };        int n = arr.Length;                 if (areElementsContiguous(arr, n))            Console.WriteLine("Yes");                 else            Console.WriteLine("No");             }     }     // This code is contributed by Vt_m.
<?php// Sorting based PHP implementation to check// whether the array contains a set of contiguous// integers // function to check whether the array contains// a set of contiguous integersfunction areElementsContiguous($arr, $n){    // Sort the array    sort($arr);         // After sorting, check if current element    // is either same as previous or is one more.    for ($i = 1; $i < $n; $i++)        if ($arr[$i] - $arr[$i - 1] > 1)            return false;         return true;} // Driver Code$arr = array( 5, 2, 3, 6,              4, 4, 6, 6 );$n = sizeof($arr); if (areElementsContiguous($arr, $n))    echo "Yes";else    echo "No";     // This code is contributed by ajit?>
<script>    // Sorting based Javascript implementation    // to check whether the array    // contains a set of contiguous    // integers         // function to check whether    // the array contains a set    // of contiguous integers    function areElementsContiguous(arr, n)    {      // Sort the array      arr.sort(function(a, b){return a - b});       // After sorting, check if      // current element is either      // same as previous or is      // one more.      for (let i = 1; i < n; i++)          if (arr[i] - arr[i - 1] > 1)              return false;       return true;    }         let arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ];    let n = arr.length;     if (areElementsContiguous(arr, n))      document.write("Yes");     else      document.write("No");   // This code is contributed by rameshtravel07.</script>
Output:  
Yes
Time Complexity: O(n Log n)
Another Approach is :- 
if we can find the minimum element and maximum element that are present in the array and use the below procedure then we can say that the array contains contiguous elements or not.
PROCEDURE :-
1) Store the elements in unordered set (So as to maintain the Time complexity of the problem i.e. O(n) ) 
2) Find the minimum element present in the array and store it in a variable say min_ele.
3) Find the maximum element present in the array and store it in a variable say max_ele.
4) Now just think a little bit we can notice that if we Subtract the min_ele from the max_ele and add 1 to the result.
5) If the the final result is equal to the size of the set then in that case we can say that the given array contains contiguous elements.
Lets take a example to understand the above procedure.
Lets say that after storing the value in the unordered set we have the values inside it from 1 to 10 (1,2,3,4,5,6,7,8,9,10). The actual order inside the unordered set is not like this I have just taken it to for easier understanding.
From the example above we can clearly say that the maximum element present in the set is 10 and minimum element present in the set is 1.
Subtracting the minimum element from the maximum element we get 9 as the result(10-1=9).
Now when we add 1 to the result and compare it with the size of the unordered set then we can say that the they are equal. (9+1=10 which is equal to the size of the unordered set).
Hence the function will return True.
Now just imagine if one of the element is not present in the unordered set (say 5) then in that case the size of unordered set is 9 then in that case 10 which is final result is not equal to the size of the unordered set. And hence the function will return False.
The Implementation of the above method is :- 
C++
// C++ implementation to check whether the array contains a// set of contiguous integers#include <bits/stdc++.h>using namespace std; // function to check whether the array contains a set of// contiguous integersbool areElementsContiguous(int arr[], int n){    // Declaring and Initialising the set simultaneously    unordered_set<int> s(arr, arr + n);    // Finding the size of the unordered set    int set_size = s.size();    // Find maximum and minimum elements.    int max = *max_element(arr, arr + n);    int min = *min_element(arr, arr + n);     int result = max - min + 1;    if (result != set_size)        return false;    return true;} // Driver programint main(){    int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    if (areElementsContiguous(arr, n))        cout << "Yes";    else        cout << "No";    return 0;}// This code is contributed by Aditya Kumar (adityakumar129)
Yes
TIME COMPLEXITY :- O(n)
SPACE COMPLEXITY :- O(n)
Efficient solution using visited array 1) Find the minimum and maximum elements. 2) Create a visited array of size max-min + 1. Initialize this array as false. 3) Traverse the given array and mark visited[arr[i] – min] as true for every element arr[i]. 4) Traverse visited array and return true if all values are true. Else return false. 
C++
Java
Python3
C#
Javascript
// C++ implementation to// check whether the array// contains a set of// contiguous integers#include <bits/stdc++.h>using namespace std; // function to check// whether the array// contains a set of// contiguous integersbool areElementsContiguous(int arr[], int n){    // Find maximum and    // minimum elements.    int max = *max_element(arr, arr + n);    int min = *min_element(arr, arr + n);     int m = max - min + 1;     // There should be at least    // m elements in array to    // make them contiguous.    if (m > n)        return false;         // Create a visited array    // and initialize false.    bool visited[m];    memset(visited, false, sizeof(visited));     // Mark elements as true.    for (int i=0; i<n; i++)    visited[arr[i] - min] = true;     // If any element is not    // marked, all elements    // are not contiguous.    for (int i=0; i<m; i++)    if (visited[i] == false)            return false;     return true;} // Driver programint main(){    int arr[] = { 5, 2, 3, 6,                  4, 4, 6, 6 };     int n = sizeof(arr) / sizeof(arr[0]);     if (areElementsContiguous(arr, n))        cout << "Yes";    else        cout << "No";     return 0;}
// Java implementation to// check whether the array// contains a set of// contiguous integersimport java.util.*; class GFG {         // function to check    // whether the array    // contains a set of    // contiguous integers    static boolean areElementsContiguous(int arr[],                                         int n)    {        // Find maximum and        // minimum elements.        int max = Integer.MIN_VALUE;        int min = Integer.MAX_VALUE;                 for(int i = 0; i < n; i++)        {            max = Math.max(max, arr[i]);            min = Math.min(min, arr[i]);        }              int m = max - min + 1;              // There should be at least        // m elements in array to        // make them contiguous.        if (m > n)            return false;                  // Create a visited array        // and initialize false.        boolean  visited[] = new boolean[n];                       // Mark elements as true.        for (int i = 0; i < n; i++)              visited[arr[i] - min] = true;              // If any element is not        // marked, all elements        // are not contiguous.        for (int i = 0; i < m; i++)           if (visited[i] == false)                return false;              return true;    }         /* Driver program  */    public static void main(String[] args)    {        int arr[] = { 5, 2, 3, 6,                      4, 4, 6, 6 };                               int n = arr.length;                 if (areElementsContiguous(arr, n))            System.out.println("Yes");                 else            System.out.println("No");                }}
# Python3 implementation to# check whether the array# contains a set of# contiguous integers # function to check# whether the array# contains a set of# contiguous integersdef areElementsContiguous(arr, n):         # Find maximum and    # minimum elements.    max1 = max(arr)    min1 = min(arr)         m = max1 - min1 + 1     # There should be at least    # m elements in array to    # make them contiguous.    if (m > n):        return False         # Create a visited array    # and initialize false     visited = [0] * m         # Mark elements as true.    for i in range(0,n) :        visited[arr[i] - min1] = True     # If any element is not    # marked, all elements    # are not contiguous.    for i in range(0, m):        if (visited[i] == False):            return False     return True # Driver programarr = [5, 2, 3, 6, 4, 4, 6, 6 ]n = len(arr) if (areElementsContiguous(arr, n)):    print("Yes")else:    print("No") # This code is contributed by Smitha Dinesh Semwal
// C# implementation to check whether// the array contains a set of// contiguous integersusing System; class GFG {         // function to check whether the    // array contains a set of    // contiguous integers    static bool areElementsContiguous(                        int []arr, int n)    {                 // Find maximum and        // minimum elements.        int max = int.MinValue;        int min = int.MaxValue;                 for(int i = 0; i < n; i++)        {            max = Math.Max(max, arr[i]);            min = Math.Min(min, arr[i]);        }             int m = max - min + 1;             // There should be at least        // m elements in array to        // make them contiguous.        if (m > n)            return false;                 // Create a visited array        // and initialize false.        bool []visited = new bool[n];                      // Mark elements as true.        for (int i = 0; i < n; i++)            visited[arr[i] - min] = true;             // If any element is not        // marked, all elements        // are not contiguous.        for (int i = 0; i < m; i++)            if (visited[i] == false)                return false;             return true;    }         /* Driver program */    public static void Main()    {        int []arr = { 5, 2, 3, 6,                    4, 4, 6, 6 };                                 int n = arr.Length;                 if (areElementsContiguous(arr, n))            Console.Write("Yes");        else            Console.Write("No");    }} // This code is contributed by nitin mittal.
<script>    // Javascript implementation to    // check whether the array    // contains a set of    // contiguous integers         // function to check whether the    // array contains a set of    // contiguous integers    function areElementsContiguous(arr, n)    {                  // Find maximum and        // minimum elements.        let max = Number.MIN_VALUE;        let min = Number.MAX_VALUE;                  for(let i = 0; i < n; i++)        {            max = Math.max(max, arr[i]);            min = Math.min(min, arr[i]);        }              let m = max - min + 1;              // There should be at least        // m elements in array to        // make them contiguous.        if (m > n)            return false;                  // Create a visited array        // and initialize false.        let visited = new Array(n);        visited.fill(false);                        // Mark elements as true.        for (let i = 0; i < n; i++)            visited[arr[i] - min] = true;              // If any element is not        // marked, all elements        // are not contiguous.        for (let i = 0; i < m; i++)            if (visited[i] == false)                return false;              return true;    }         let arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ];                              let n = arr.length;     if (areElementsContiguous(arr, n))      document.write("Yes");    else      document.write("No");     </script>
Output: 
Yes
Time Complexity: O(n)
Efficient solution using the hash table Insert all the elements in the hash table. Now pick the first element and keep on incrementing in its value by 1 till you find a value not present in the hash table. Again pick the first element and keep on decrementing in its value by 1 till you find a value not present in the hash table. Get the count of elements (obtained by this process) that are present in the hash table. If the count equals hash size print “Yes” else “No”. 
C++
Java
Python
C#
Javascript
// C++ implementation to check whether the array// contains a set of contiguous integers#include <bits/stdc++.h>using namespace std; // Function to check whether the array contains// a set of contiguous integersbool areElementsContiguous(int arr[], int n){    // Storing elements of 'arr[]' in a hash    // table 'us'      unordered_set<int> us;    for (int i = 0; i < n; i++)        us.insert(arr[i]);     // as arr[0] is present in 'us'    int count = 1;     // starting with previous smaller element    // of arr[0]    int curr_ele = arr[0] - 1;     // if 'curr_ele' is present in 'us'    while (us.find(curr_ele) != us.end()) {         // increment count        count++;         // update 'curr_ele"        curr_ele--;    }     // starting with next greater element    // of arr[0]    curr_ele = arr[0] + 1;     // if 'curr_ele' is present in 'us'    while (us.find(curr_ele) != us.end()) {         // increment count        count++;         // update 'curr_ele"        curr_ele++;    }     // returns true if array contains a set of    // contiguous integers else returns false    return (count == (int)(us.size()));} // Driver program to test aboveint main(){    int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    if (areElementsContiguous(arr, n))        cout << "Yes";    else        cout << "No";     return 0;}
// Java implementation to check whether the array// contains a set of contiguous integersimport java.io.*;import java.util.*; class GFG {    // Function to check whether the array    // contains a set of contiguous integers    static Boolean areElementsContiguous(int arr[], int n)    {        // Storing elements of 'arr[]' in        // a hash table 'us'        HashSet<Integer> us = new HashSet<Integer>();                 for (int i = 0; i < n; i++)            us.add(arr[i]);         // As arr[0] is present in 'us'        int count = 1;         // Starting with previous smaller        // element of arr[0]        int curr_ele = arr[0] - 1;         // If 'curr_ele' is present in 'us'        while (us.contains(curr_ele) == true) {             // increment count            count++;             // update 'curr_ele"            curr_ele--;        }         // Starting with next greater        // element of arr[0]        curr_ele = arr[0] + 1;         // If 'curr_ele' is present in 'us'        while (us.contains(curr_ele) == true) {             // increment count            count++;             // update 'curr_ele"            curr_ele++;        }         // Returns true if array contains a set of        // contiguous integers else returns false        return (count == (us.size()));    }     // Driver Code    public static void main(String[] args)    {        int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 };        int n = arr.length;                 if (areElementsContiguous(arr, n))            System.out.println("Yes");        else            System.out.println("No");    }} // This code is contributed by 'Gitanjali'.
# Python implementation to check whether the array# contains a set of contiguous integers # Function to check whether the array# contains a set of contiguous integersdef areElementsContiguous(arr):    # Storing elements of 'arr[]' in a hash table 'us'    us = set()    for i in arr: us.add(i)     # As arr[0] is present in 'us'    count = 1     # Starting with previous smaller element of arr[0]    curr_ele = arr[0] - 1     # If 'curr_ele' is present in 'us'    while curr_ele in us:         # Increment count        count += 1         # Update 'curr_ele"        curr_ele -= 1     # Starting with next greater element of arr[0]    curr_ele = arr[0] + 1     # If 'curr_ele' is present in 'us'    while curr_ele in us:         # Increment count        count += 1         # Update 'curr_ele"        curr_ele += 1     # Returns true if array contains a set of    # contiguous integers else returns false    return (count == len(us)) # Driver codearr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]if areElementsContiguous(arr): print("Yes")else: print("No") # This code is contributed by 'Ansu Kumari'
using System;using System.Collections.Generic; // c# implementation to check whether the array// contains a set of contiguous integers public class GFG{    // Function to check whether the array     // contains a set of contiguous integers    public static bool? areElementsContiguous(int[] arr, int n)    {        // Storing elements of 'arr[]' in         // a hash table 'us'        HashSet<int> us = new HashSet<int>();         for (int i = 0; i < n; i++)        {            us.Add(arr[i]);        }         // As arr[0] is present in 'us'        int count = 1;         // Starting with previous smaller         // element of arr[0]        int curr_ele = arr[0] - 1;         // If 'curr_ele' is present in 'us'        while (us.Contains(curr_ele) == true)        {             // increment count            count++;             // update 'curr_ele"            curr_ele--;        }         // Starting with next greater         // element of arr[0]        curr_ele = arr[0] + 1;         // If 'curr_ele' is present in 'us'        while (us.Contains(curr_ele) == true)        {             // increment count            count++;             // update 'curr_ele"            curr_ele++;        }         // Returns true if array contains a set of        // contiguous integers else returns false        return (count == (us.Count));    }     // Driver Code    public static void Main(string[] args)    {        int[] arr = new int[] {5, 2, 3, 6, 4, 4, 6, 6};        int n = arr.Length;         if (areElementsContiguous(arr, n).Value)        {            Console.WriteLine("Yes");        }        else        {            Console.WriteLine("No");        }    }} // This code is contributed by Shrikant13
<script> // Javascript implementation to check whether the array// contains a set of contiguous integers // Function to check whether the array contains// a set of contiguous integersfunction areElementsContiguous(arr, n){    // Storing elements of 'arr[]' in a hash    // table 'us'      var us = new Set();    for (var i = 0; i < n; i++)        us.add(arr[i]);     // as arr[0] is present in 'us'    var count = 1;     // starting with previous smaller element    // of arr[0]    var curr_ele = arr[0] - 1;     // if 'curr_ele' is present in 'us'    while (us.has(curr_ele)) {         // increment count        count++;         // update 'curr_ele"        curr_ele--;    }     // starting with next greater element    // of arr[0]    curr_ele = arr[0] + 1;     // if 'curr_ele' is present in 'us'    while (us.has(curr_ele)) {         // increment count        count++;         // update 'curr_ele"        curr_ele++;    }     // returns true if array contains a set of    // contiguous integers else returns false    return (count == (us.size));} // Driver program to test abovevar arr = [5, 2, 3, 6, 4, 4, 6, 6];var n = arr.length;if (areElementsContiguous(arr, n))    document.write( "Yes");else    document.write( "No"); // This code is contributed by rutvik_56.</script>
Output :  
Yes
Time Complexity: O(n). Auxiliary Space: O(n).
This method requires only one traversal of the given array. It traverses the hash table after array traversal (the hash table contains only distinct elements). 
nitin mittal
shrikanth13
jit_t
rameshtravel07
divyeshrabadiya07
rutvik_56
sweetyty
surinderdawra388
adityakumar129
simmytarika5
Amazon
java-hashset
Arrays
Hash
Sorting
Amazon
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum