Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Replace every element of array with sum of elements on its right side
Next article icon

Ceiling in right side for every element in an array

Last Updated : 22 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 nested loops. We pick an outer element one by one. For every picked element, we traverse the right side array and find the closest greater or equal element. Time complexity of this solution is O(n*n)

A better solution is to use sorting. We sort all elements, then for every element, traverse toward the right until we find a greater element (Note that there can be multiple occurrences of an element).

An efficient solution is to use Self Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and ceiling operations in O(Log n) time.

Implementation:

C++
// C++ program to find ceiling on right side for // every element. #include <bits/stdc++.h> using namespace std;  void closestGreater(int arr[], int n) {     set<int> s;     vector<int> ceilings;      // Find smallest greater or equal element     // for every array element     for (int i = n - 1; i >= 0; i--) {         auto greater = s.lower_bound(arr[i]);         if (greater == s.end())             ceilings.push_back(-1);         else             ceilings.push_back(*greater);         s.insert(arr[i]);     }      for (int i = n - 1; i >= 0; i--)         cout << ceilings[i] << " "; }  int main() {     int arr[] = { 50, 20, 200, 100, 30 };     closestGreater(arr, 5);     return 0; } 
Java
// Java program to find ceiling on right side for // every element. import java.util.*;  class TreeSetDemo {     public static void closestGreater(int[] arr)     {         int n = arr.length;         TreeSet<Integer> ts = new TreeSet<Integer>();         ArrayList<Integer> ceilings = new ArrayList<Integer>(n);          // Find smallest greater or equal element         // for every array element         for (int i = n - 1; i >= 0; i--) {             Integer greater = ts.ceiling(arr[i]);             if (greater == null)                 ceilings.add(-1);             else                 ceilings.add(greater);             ts.add(arr[i]);         }          for (int i = n - 1; i >= 0; i--)             System.out.print(ceilings.get(i) + " ");     }      public static void main(String[] args)     {         int[] arr = { 50, 20, 200, 100, 30 };         closestGreater(arr);     } } 
Python3
# Python program to find ceiling on right side for # every element. import bisect  def closestGreater(arr, n):     s = []     ceilings = []      # Find smallest greater or equal element     # for every array element     for i in range(n - 1, -1, -1):         greater = bisect.bisect_left(s, arr[i])         if greater == len(s):             ceilings.append(-1)         else:             ceilings.append(s[greater])         s.insert(greater, arr[i])      for i in range(n - 1, -1, -1):         print(ceilings[i], end=" ")  arr = [50, 20, 200, 100, 30] closestGreater(arr, 5)  # This code is contributed by codebraxnzt 
C#
// C# program to find ceiling on right side for // every element. using System; using System.Collections.Generic;  public class TreeSetDemo {   public static void closestGreater(int[] arr)   {     int n = arr.Length;     SortedSet<int> ts = new SortedSet<int>();     List<int> ceilings = new List<int>(n);      // Find smallest greater or equal element     // for every array element     for (int i = n - 1; i >= 0; i--) {       int greater = lower_bound(ts, arr[i]);       if (greater == -1)         ceilings.Add(-1);       else         ceilings.Add(greater);       ts.Add(arr[i]);     }     ceilings.Sort((a,b)=>a-b);     for (int i = n - 1; i >= 0; i--)       Console.Write(ceilings[i] + " ");   }   public static int lower_bound(SortedSet<int> s, int val)   {     List<int> temp = new List<int>();     temp.AddRange(s);     temp.Sort();     temp.Reverse();      if (temp.IndexOf(val) + 1 == temp.Count)       return -1;     else if(temp[temp.IndexOf(val) +1]>val)       return -1;     else       return temp[temp.IndexOf(val) +1];   }    public static void Main(String[] args)   {     int[] arr = { 50, 20, 200, 100, 30 };     closestGreater(arr);   } }  // This code is contributed by Rajput-Ji  
JavaScript
// JavaScript code for the above approach  function closestGreater(arr, n) {   let s = [];   let ceilings = [];    // Find smallest greater or equal element   // for every array element   for (let i = n - 1; i >= 0; i--) {     let greater = bisect_left(s, arr[i]);     if (greater == s.length) {       ceilings.push(-1);     } else {       ceilings.push(s[greater]);     }     s.splice(greater, 0, arr[i]);   }   let temp = [];   for (let i = n - 1; i >= 0; i--) {     temp.push(ceilings[i]);   }   console.log(temp.join(" ")); }  function bisect_left(s, x) {   let lo = 0;   let hi = s.length;   while (lo < hi) {     let mid = Math.floor((lo + hi) / 2);     if (s[mid] < x) {       lo = mid + 1;     } else {       hi = mid;     }   }   return lo; }  let arr = [50, 20, 200, 100, 30]; closestGreater(arr, 5);   // This code is contributed by Prince Kumar 

Output
100 30 -1 -1 -1 

Time Complexity: O(n Log n)
Auxiliary Space: O(n) 


Next Article
Replace every element of array with sum of elements on its right side
author
kartik
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Ceiling of every element in same array
    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
    15+ min read
  • Next Greater Element (NGE) for every element in given Array
    Given an array arr[] of integers, the task is to find the Next Greater Element for each element of the array in order of their appearance in the array. Note: The Next Greater Element for an element x is the first greater element on the right side of x in the array. Elements for which no greater elem
    9 min read
  • 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
  • Count of larger elements on right side of each element in an array
    Given an array arr[] consisting of N integers, the task is to count the number of greater elements on the right side of each array element. Examples: Input: arr[] = {3, 7, 1, 5, 9, 2} Output: {3, 1, 3, 1, 0, 0} Explanation: For arr[0], the elements greater than it on the right are {7, 5, 9}. For arr
    15+ min read
  • Replace every element of array with sum of elements on its right side
    Given an array arr[], the task is to replace every element of the array with the sum of elements on its right side.Examples: Input: arr[] = {1, 2, 5, 2, 2, 5} Output: 16 14 9 7 5 0 Input: arr[] = {5, 1, 3, 2, 4} Output: 10 9 6 4 0 Naive Approach: A simple approach is to run two loops, Outer loop to
    8 min read
  • Print all Distinct (Unique) Elements in given Array
    Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2} Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4
    11 min read
  • Print greater elements present on the left side of each array element
    Given an array arr[] consisting of N distinct integers, the task is to print for each array element, all the greater elements present on its left. Examples: Input: arr[] = {5, 3, 9, 0, 16, 12}Output:5: 3: 59: 0: 9 5 316: 12: 16 Input: arr[] = {1, 2, 0}Output:1: 2: 0: 2 1 Naive Approach: The simplest
    10 min read
  • Closest greater or same value on left side for every element in array
    Given an array arr[] of size n. For each element in the array, find the value wise closest element to its left that is greater than or equal to the current element. If no such element exists, return -1 for that position. Examples: Input : arr[] = [10, 5, 11, 6, 20, 12]Output : [-1, 10, -1, 10, -1, 2
    9 min read
  • Search for an element in a Mountain Array
    Given a mountain array arr[] and an integer X, the task is to find the smallest index of X in the given array. If no such index is found, print -1. Examples: Input: arr = {1, 2, 3, 4, 5, 3, 1}, X = 3Output: 2Explanation: The smallest index of X(= 3) in the array is 2. Therefore, the required output
    14 min read
  • Queries on Left and Right Circular shift on array
    Given an array arr[] of N integers. There are three types of commands: 1 x: Right Circular Shift the array x times. If an array is a[0], a[1], ...., a[n - 1], then after one right circular shift the array will become a[n - 1], a[0], a[1], ...., a[n - 2].2 y: Left Circular Shift the array y times. If
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences