Ceiling of every element in same array
Last Updated :
16 Sep, 2023
Given an array of integers, find the closest greater or same element for every element. If all elements are smaller for an element, then print -1
Examples:
Input : arr[] = {10, 5, 11, 10, 20, 12}
Output : 10 10 12 10 -1 20
Note that there are multiple occurrences of 10, so ceiling of 10 is 10 itself.
Input : arr[] = {6, 11, 7, 8, 20, 12}
Output : 7 12 8 11 -1 20
A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse remaining array and find closest greater element. Time complexity of this solution is O(n*n)
Algorithm:
- Create a vector to store the result.
- Loop through every element of the array from i = 0 to n-1.
a. Initialize the variable ‘closest’ as INT_MAXLoop through all elements of the array from j = 0 to n-1
i. If i and j are the same, continue to the next iteration of the loop
ii. If arr[j] is greater than or equal to arr[i], update the variable closest with minimum of closest and arr[j]
b. If closest is still INT_MAX, push -1 to the result vector else push closest
3. Return the result vector
4. In the main function:
Create an array of integers arr[] of size n
Initialize n as the size of the array arr[]
Call the closestGreaterOrSame function and store the result in a vector called ‘result’
Loop through the result vector and print the elements
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > closestGreaterOrSame( int arr[], int n) {
vector< int > res;
for ( int i = 0; i < n; i++) {
int closest = INT_MAX;
for ( int j = 0; j < n; j++) {
if (i == j)
continue ;
if (arr[j] >= arr[i]) {
closest = min(closest, arr[j]);
}
}
if ( closest == INT_MAX)
res.push_back(-1);
else
res.push_back(closest);
}
return res;
}
int main()
{
int arr[] = { 6, 11, 7, 8, 20, 12 };
int n = sizeof (arr) / sizeof (arr[0]);
vector< int > result = closestGreaterOrSame(arr, n);
for ( int i = 0; i < result.size(); i++)
cout << result[i] << " " ;
cout << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static ArrayList<Integer>
closestGreaterOrSame( int arr[], int n)
{
ArrayList<Integer> res = new ArrayList<Integer>();
for ( int i = 0 ; i < n; i++) {
int closest = Integer.MAX_VALUE;
for ( int j = 0 ; j < n; j++) {
if (i == j)
continue ;
if (arr[j] >= arr[i]) {
closest = Math.min(closest, arr[j]);
}
}
if (closest == Integer.MAX_VALUE)
res.add(- 1 );
else
res.add(closest);
}
return res;
}
public static void main(String[] args)
{
int arr[] = { 6 , 11 , 7 , 8 , 20 , 12 };
int n = arr.length;
ArrayList<Integer> result
= closestGreaterOrSame(arr, n);
for ( int i = 0 ; i < result.size(); i++)
System.out.print(result.get(i) + " " );
System.out.println();
}
}
|
Python3
def closestGreaterOrSame(arr):
n = len (arr)
res = []
for i in range (n):
closest = float ( 'inf' )
for j in range (n):
if i = = j:
continue
if arr[j] > = arr[i]:
closest = min (closest, arr[j])
if closest = = float ( 'inf' ):
res.append( - 1 )
else :
res.append(closest)
return res
arr = [ 6 , 11 , 7 , 8 , 20 , 12 ]
result = closestGreaterOrSame(arr)
print ( " " .join( map ( str , result)))
|
C#
using System;
using System.Collections.Generic;
class GFG {
public static List< int >
closestGreaterOrSame( int [] arr, int n)
{
List< int > res = new List< int >();
for ( int i = 0; i < n; i++) {
int closest = int .MaxValue;
for ( int j = 0; j < n; j++) {
if (i == j)
continue ;
if (arr[j] >= arr[i]) {
closest = Math.Min(closest, arr[j]);
}
}
if (closest == int .MaxValue)
res.Add(-1);
else
res.Add(closest);
}
return res;
}
public static void Main( string [] args)
{
int [] arr = { 6, 11, 7, 8, 20, 12 };
int n = arr.Length;
List< int > result
= closestGreaterOrSame(arr, n);
for ( int i = 0; i < result.Count; i++)
Console.WriteLine(result[i] + " " );
Console.WriteLine();
}
}
|
Javascript
function closestGreaterOrSame(arr) {
const n = arr.length;
const res = [];
for (let i = 0; i < n; i++) {
let closest = Infinity;
for (let j = 0; j < n; j++) {
if (i === j)
continue ;
if (arr[j] >= arr[i]) {
closest = Math.min(closest, arr[j]);
}
}
if (closest === Infinity)
res.push(-1);
else
res.push(closest);
}
return res;
}
const arr = [6, 11, 7, 8, 20, 12];
const result = closestGreaterOrSame(arr);
console.log(result.join( " " ));
|
Time Complexity: O(N*N) as two nested loops are executing. Here, N is size of the input array.
Space Complexity: O(1) as no extra space has been used. Note here res vector space is ignored as it is the resultnt vector.
Another Approach using Hashing:
Solution is to store the answer for each element in a map (say res). And this can be done by using second map (say m) which will store frequency of elements and automatically sort it according to keys. Then traverse map m and find answer to each key and store answer in map res[key].
C++
#include <bits/stdc++.h>
using namespace std;
map< int , int > m;
map< int , int > res;
void printPrevGreater( int arr[], int n)
{
for ( int i = 0; i < n; i++) {
m[arr[i]]++;
}
int c = 0;
int prev;
int f = 0;
for ( auto i = m.begin(); i != m.end(); i++) {
if (f == 1) {
res[prev] = i->first;
f = 0;
c++;
}
if (i->second == 1) {
f = 1;
prev = i->first;
}
else if (i->second
> 1) {
res[i->first] = i->first;
c++;
f = 0;
}
}
if (c < n) {
res[prev] = -1;
}
for ( int i = 0; i < n; i++) {
cout << res[arr[i]] << " " ;
}
}
int main()
{
int arr[] = { 6, 11, 7, 8, 20, 12 };
int n = sizeof (arr) / sizeof (arr[0]);
printPrevGreater(arr, n);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static Map<Integer,Integer> m = new TreeMap<>();
static Map<Integer,Integer> res = new TreeMap<>();
static void printPrevGreater( int arr[], int n)
{
for ( int i = 0 ; i < n; i++) {
if (m.containsKey(arr[i])){
m.put(arr[i], m.get(arr[i])+ 1 );
}
else m.put(arr[i], 1 );
}
int c = 0 ;
int prev = 0 ;
int f = 0 ;
for (Map.Entry<Integer, Integer>entry : m.entrySet()) {
if (f == 1 ) {
res.put(prev,entry.getKey());
f = 0 ;
c++;
}
if (entry.getValue() == 1 ) {
f = 1 ;
prev = entry.getKey();
}
else if (entry.getValue() > 1 ) {
res.put(entry.getKey() , entry.getKey());
c++;
f = 0 ;
}
}
if (c < n) {
res.put(prev , - 1 );
}
for ( int i = 0 ; i < n; i++) {
System.out.printf( "%d " ,res.get(arr[i]));
}
}
public static void main(String args[])
{
int arr[] = { 6 , 11 , 7 , 8 , 20 , 12 };
int n = arr.length;
printPrevGreater(arr, n);
}
}
|
Python3
m = {};
res = {};
def printPrevGreater(arr, n):
for i in range (n):
if arr[i] not in m:
m[arr[i]] = 0
m[arr[i]] + = 1
c = 0 ;
f = 0 ;
for i in sorted (m) :
if (f = = 1 ) :
res[prev] = int (i)
f = 0 ;
c + = 1 ;
if (m[i] = = 1 ):
f = 1 ;
prev = int (i);
elif (m[i] > 1 ):
res[ int (i)] = int (i);
c + = 1
f = 0 ;
if (c < n):
res[prev] = - 1 ;
for i in range (n):
print (res[arr[i]], end = " " );
arr = [ 6 , 11 , 7 , 8 , 20 , 12 ];
n = len (arr);
printPrevGreater(arr, n);
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static SortedDictionary< int , int > m =
new SortedDictionary< int , int >();
static SortedDictionary< int , int > res =
new SortedDictionary< int , int >();
static void printPrevGreater( int [] arr, int n)
{
for ( int i = 0; i < n; i++) {
if (m.ContainsKey(arr[i])){
m[arr[i]] += 1;
}
else m[arr[i]] = 1;
}
int c = 0;
int prev = 0;
int f = 0;
foreach ( var entry in m) {
if (f == 1) {
res[prev] = entry.Key;
f = 0;
c++;
}
if (entry.Value == 1) {
f = 1;
prev = entry.Key;
}
else if (entry.Value > 1) {
res[entry.Key] = entry.Key;
c++;
f = 0;
}
}
if (c < n) {
res[prev] = -1;
}
for ( int i = 0; i < n; i++) {
Console.Write(res[arr[i]] + " " );
}
}
public static void Main( string [] args)
{
int [] arr = { 6, 11, 7, 8, 20, 12 };
int n = arr.Length;
printPrevGreater(arr, n);
}
}
|
Javascript
let m = {};
let res = {};
function printPrevGreater(arr, n)
{
for ( var i = 0; i < n; i++) {
if (!m.hasOwnProperty(arr[i]))
m[arr[i]] = 0;
m[arr[i]]++;
}
let c = 0;
let prev;
let f = 0;
for (const i in m) {
if (f == 1) {
res[prev] = parseInt(
i);
f = 0;
c++;
}
if (m[i] == 1) {
f = 1;
prev = parseInt(i);
}
else if (m[i] > 1) {
res[parseInt(i)] = parseInt(i);
c++;
f = 0;
}
}
if (c < n) {
res[prev]
= -1;
}
for ( var i = 0; i < n; i++) {
process.stdout.write(res[arr[i]] + " " );
}
}
let arr = [ 6, 11, 7, 8, 20, 12 ];
let n = arr.length;
printPrevGreater(arr, n);
|
Time Complexity: O(n log(n)).
Auxiliary Space: O(n)
A better solution is to sort the array and create a sorted copy, then do binary search for floor. We traverse the array, for every element we search for the first greater element. In C++ upper_bound() serves this purpose.
Below is the implementation of the above approach
C++
#include <bits/stdc++.h>
using namespace std;
void printPrevGreater( int arr[], int n)
{
if (n == 1) {
cout << "-1" ;
return ;
}
vector< int > v(arr, arr + n);
sort(v.begin(), v.end());
for ( int i = 0; i < n; i++) {
auto it = upper_bound(v.begin(), v.end(), arr[i]);
if ((it - 1) != v.begin() && *(it - 2) == arr[i]) {
cout << arr[i] << " " ;
}
else if (it != v.end())
cout << *it << " " ;
else
cout << -1 << " " ;
}
}
int main()
{
int arr[] = {10, 5, 11, 10, 20, 12};
int n = sizeof (arr) / sizeof (arr[0]);
printPrevGreater(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG
{
static void printPrevGreater( int arr[], int n)
{
if (n == 1 )
{
System.out.println( "-1" );
return ;
}
int v[] = Arrays.copyOf(arr, arr.length);
Arrays.sort(v);
for ( int i = 0 ; i < n; i++)
{
int it = Arrays.binarySearch(v,arr[i]);
it++;
if ((it - 1 ) != 0 && v[it - 2 ] == arr[i])
{
System.out.print(arr[i] + " " );
}
else if (it != v.length)
System.out.print(v[it] + " " );
else
System.out.print(- 1 + " " );
}
}
public static void main(String[] args)
{
int arr[] = { 10 , 5 , 11 , 10 , 20 , 12 };
int n = arr.length;
printPrevGreater(arr, n);
}
}
|
Python3
import bisect
def printPrevGreater(arr, n):
if n = = 1 :
print ( "-1" )
return
v = list (arr)
v.sort()
for i in range (n):
it = bisect.bisect_right(v, arr[i])
if (it - 1 ) ! = 0 and v[it - 2 ] = = arr[i]:
print (arr[i], end = " " )
elif it < = n - 1 :
print (v[it], end = " " )
else :
print ( - 1 , end = " " )
if __name__ = = "__main__" :
arr = [ 10 , 5 , 11 , 10 , 20 , 12 ]
n = len (arr)
printPrevGreater(arr, n)
|
C#
using System;
class GFG
{
static void printPrevGreater( int []arr, int n)
{
if (n == 1)
{
Console.Write( "-1" );
return ;
}
int []v = new int [arr.GetLength(0)];
Array.Copy(arr, v, arr.GetLength(0));
Array.Sort(v);
for ( int i = 0; i < n; i++)
{
int it = Array.BinarySearch(v, arr[i]);
it++;
if ((it - 1) != 0 && v[it - 2] == arr[i])
{
Console.Write(arr[i] + " " );
}
else if (it != v.Length)
Console.Write(v[it] + " " );
else
Console.Write(-1 + " " );
}
}
public static void Main(String[] args)
{
int []arr = {10, 5, 11, 10, 20, 12};
int n = arr.Length;
printPrevGreater(arr, n);
}
}
|
Javascript
function upper_bound(arr, N, X)
{
let mid;
let low = 0;
let high = N;
while (low < high) {
mid = low + Math.floor((high - low) / 2);
if (X >= arr[mid]) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
if (low < N && arr[low] <= X) {
low++;
}
return low;
}
function printPrevGreater(arr, n)
{
if (n == 1) {
process.stdout.write( "-1" );
return ;
}
let v = [...arr];
v.sort();
for ( var i = 0; i < n; i++) {
let it = upper_bound(v, n, arr[i]);
if ((it - 1) != 0 && v[it - 2] === arr[i]) {
process.stdout.write(arr[i] + " " );
}
else if (it < n)
process.stdout.write(v[it] + " " );
else
process.stdout.write( "-1" );
}
}
let arr = [10, 5, 11, 10, 20, 12];
let n = arr.length;
printPrevGreater(arr, n);
|
Time Complexity : O(n Log n)
Auxiliary Space : O(n)
Similar Reads
Floor of every element in same array
Given an array of integers, find the closest smaller or same element for every element. If all elements are greater for an element, then print -1. We may assume that the array has at least two elements. Examples: Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 -1 10 10 12 11 Note that there are
14 min read
Ceiling in right side for every element in an array
Given an array of integers, find the closest greater element for every element. If there is no greater element then print -1 Examples: Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 10 12 12 -1 -1 Input : arr[] = {50, 20, 200, 100, 30} Output : 100 30 -1 -1 -1 A simple solution is to run two ne
4 min read
Counting frequencies of array elements
Given an array which may contain duplicates, print all elements and their frequencies. Examples: Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}Output : 10 3 20 4 5 1Input : arr[] = {10, 20, 20}Output : 10 1 20 2 A simple solution is to run two loops. For every item count number of times, it occurs.
15+ min read
Count of smaller or equal elements in sorted array
Given a sorted array of size n. Find a number of elements that are less than or equal to a given element. Examples: Input : arr[] = {1, 2, 4, 5, 8, 10} key = 9 Output : 5 Elements less than or equal to 9 are 1, 2, 4, 5, 8 therefore result will be 5. Input : arr[] = {1, 2, 2, 2, 5, 7, 9} key = 2 Outp
15+ min read
Frequency of an element in an array
Given an array, a[], and an element x, find a number of occurrences of x in a[]. Examples: Input : a[] = {0, 5, 5, 5, 4} x = 5Output : 3Input : a[] = {1, 2, 3} x = 4Output : 0 Unsorted ArrayThe idea is simple, we initialize count as 0. We traverse the array in a linear fashion. For every element tha
9 min read
Print sorted distinct elements of array
Given an array that might contain duplicates, print all distinct elements in sorted order. Examples: Input : 1, 3, 2, 2, 1Output : 1 2 3Input : 1, 1, 1, 2, 2, 3Output : 1 2 3The simple Solution is to sort the array first, then traverse the array and print only first occurrences of elements. Algorith
6 min read
Count Distinct Elements In Every Window of Size K
Given an array arr[] of size n and an integer k, return the count of distinct numbers in all windows of size k. Examples: Input: arr[] = [1, 2, 1, 3, 4, 2, 3], k = 4Output: [3, 4, 4, 3]Explanation: First window is [1, 2, 1, 3], count of distinct numbers is 3. Second window is [2, 1, 3, 4] count of d
10 min read
Find the frequency of each element in a sorted array
Given a sorted array, arr[] consisting of N integers, the task is to find the frequencies of each array element. Examples: Input: arr[] = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10} Output: Frequency of 1 is: 3 Frequency of 2 is: 1 Frequency of 3 is: 2 Frequency of 5 is: 2 Frequency of 8 is: 3 Frequ
10 min read
Count greater elements on the left side of every array element
Given an array arr[] of distinct integers of size N, the task is to print the count of greater elements on the left side of each array element. Examples : Input: arr[] = {12, 1, 2, 3, 0, }Output: 0 1 1 1 4Explanation:For index 0, no greater element exists on the left side.For index 1, {12} is greate
7 min read
Peak Element in Array
Given an array arr[] where no two adjacent elements are same, find the index of a peak element. An element is considered to be a peak element if it is strictly greater than its adjacent elements. If there are multiple peak elements, return the index of any one of them. Note: Consider the element bef
13 min read