Integers - Missing Range

 Integers - Missing Range 

PROBLEM STATEMENT :

The program must accept N sorted (in ascending order) integers as the input. The program must print the missing range of values as the output. If none of the values are missing the program must print -1 as the output. 

Boundary Condition(s): 

2 <= N <= 10^4 

Input Format: 

The first line contains N. 

The second line contains N integer values separated by a space. 

Output Format: 

The first line contains -1 or the missing range of values separated by a space. 

Example Input/Output 1: 
Input: () 
5 
1 2 5 6 12 
Output: 3-4 7-11

Explanation: 

The missing values are 3,4. Hence the range is printed as 3-4. 

The next missing values are 7,8,9,10,11. Hence the range is printed as 7-11. 

Example Input/Output 2: 
Input: () 
6 
1 2 3 5 6 7 
Output: 4-4

Example Input/Output 3: 
Input: () 
7 
1 2 3 4 5 6 7 
Output: -1




SOLUTION :

C (Programming Language)


      

#include<stdio.h> #include<stdlib.h> int main() { int n,i,a,startRange=1,flag=-1; scanf("%d",&n); for(i=0;i<n;++i) { scanf("%d",&a); if(startRange!=a) { printf("%d-%d ",startRange,a-1); startRange=a+1; flag=1; } else { startRange+=1; } } if(flag==-1) printf("-1"); }



C++ (CPP)

       

#include <bits/stdc++.h> using namespace std; int main(int argc, char** argv) { int n,a,i,startRange=1,flag=0; cin>>n; for(i=0;i<n;++i) { cin>>a; if(startRange!=a) { cout<<startRange<<"-"<<a-1<<" "; startRange=a+1; flag=1; } else { startRange+=1; } } if(flag==0) cout<<"-1"; }



JAVA

       

import java.util.*; public class Hello { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(),a,i,startRange=1,flag=0; for(i=0;i<n;++i) { a=sc.nextInt(); if(startRange!=a) { System.out.print(startRange+"-"+(a-1)+" "); startRange=a+1; flag=1; } else { startRange+=1; } } if(flag==0) System.out.print("-1"); } }



PYTHON

       

n=int(input()) l=list(map(int,input().split())) flag=0 startRange=1 for i in range(n): if startRange!=l[i]: print(startRange,l[i]-1,sep='-',end=' ') startRange=l[i]+1 flag=1 else: startRange+=1 if flag==0: print(-1)



Never Stop Learning !!


Comments

Popular posts from this blog

DP (1) - Count number of ways to cover a distance

Zero Insert After K Times One

Left Number Twice Right