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:
Find closest greater value for every element in array
Next article icon

Closest greater or same value on left side for every element in array

Last Updated : 25 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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, 20]
Explanation: The first element has nothing on the left side, so the answer for first is -1. 
Second, element 5 has 10 on the left, so the answer is 10. 
Third element 11 has nothing greater or the same, so the answer is -1. 
Fourth element 6 has 10 as value wise closest, so the answer is 10.
Similarly, we get values for the fifth and sixth elements.

Input : arr[] = [1, 2, 3, 4, 5]
Output : [-1, -1, -1, -1, -1]
Explanation: The given array is arranged in strictly increasing order, and all the elements on left of any element are smaller. Thus no index has any value greater or equal in its left.

Input : arr[] = [5, 4, 3, 2, 1]
Output : [-1, 5, 4, 3, 2]

[Naive Approach] – Using Nested Loops – O(n^2) Time and O(1) Auxiliary Space

A idea is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse toward the left of it and find the closest (value-wise) greater element.

C++
#include <bits/stdc++.h> using namespace std;  // Function to find the closest greater element // on the left of every element of the array vector<int> closestGreater(vector<int> &arr) {     int n = arr.size();      // to store the results     vector<int> res(n, -1);      for (int i = 1; i < n; i++) {          // stores the minimum difference         int diff = INT_MAX;          // traverse left side to i-th element         for (int j = 0; j < i; j++) {             if (arr[j] >= arr[i])                 diff = min(diff, arr[j] - arr[i]);         }          // if greater or equal value exists         if (diff != INT_MAX)             res[i] = arr[i] + diff;     }      return res; }  int main() {     vector<int> arr = { 10, 5, 11, 6, 20, 12 };     vector<int> res = closestGreater(arr);     for(auto i:res) {         cout<<i<<" ";     }     return 0; } 
Java
// Function to find the closest greater element // on the left of every element of the array import java.util.*;  class GfG {      // Function to find the closest greater element     static int[] closestGreater(int[] arr) {         int n = arr.length;          // to store the results         int[] res = new int[n];         for (int i = 0; i < n; i++) {             res[i] = -1;         }          for (int i = 1; i < n; i++) {              // stores the minimum difference             int diff = Integer.MAX_VALUE;              // traverse left side to i-th element             for (int j = 0; j < i; j++) {                 if (arr[j] >= arr[i])                     diff = Math.min(diff, arr[j] - arr[i]);             }              // if greater or equal value exists             if (diff != Integer.MAX_VALUE)                 res[i] = arr[i] + diff;         }          return res;     }      public static void main(String[] args) {         int[] arr = {10, 5, 11, 6, 20, 12};         int[] res = closestGreater(arr);         for (int i : res) {             System.out.print(i + " ");         }     } } 
Python
# Function to find the closest greater element # on the left of every element of the array def closestGreater(arr):     n = len(arr)      # to store the results     res = [-1] * n      for i in range(1, n):          # stores the minimum difference         diff = float('inf')          # traverse left side to i-th element         for j in range(i):             if arr[j] >= arr[i]:                 diff = min(diff, arr[j] - arr[i])          # if greater or equal value exists         if diff != float('inf'):             res[i] = arr[i] + diff      return res  if __name__ == "__main__":     arr = [10, 5, 11, 6, 20, 12]     res = closestGreater(arr)     for i in res:         print(i, end=" ") 
C#
// Function to find the closest greater element // on the left of every element of the array using System;  class GfG {      // Function to find the closest greater element     static int[] closestGreater(int[] arr) {         int n = arr.Length;          // to store the results         int[] res = new int[n];         for (int i = 0; i < n; i++) {             res[i] = -1;         }          for (int i = 1; i < n; i++) {              // stores the minimum difference             int diff = int.MaxValue;              // traverse left side to i-th element             for (int j = 0; j < i; j++) {                 if (arr[j] >= arr[i])                     diff = Math.Min(diff, arr[j] - arr[i]);             }              // if greater or equal value exists             if (diff != int.MaxValue)                 res[i] = arr[i] + diff;         }          return res;     }      static void Main() {         int[] arr = {10, 5, 11, 6, 20, 12};         int[] res = closestGreater(arr);         foreach (int i in res) {             Console.Write(i + " ");         }     } } 
JavaScript
// Function to find the closest greater element // on the left of every element of the array function closestGreater(arr) {     let n = arr.length;      // to store the results     let res = new Array(n).fill(-1);      for (let i = 1; i < n; i++) {          // stores the minimum difference         let diff = Infinity;          // traverse left side to i-th element         for (let j = 0; j < i; j++) {             if (arr[j] >= arr[i])                 diff = Math.min(diff, arr[j] - arr[i]);         }          // if greater or equal value exists         if (diff !== Infinity)             res[i] = arr[i] + diff;     }      return res; }  let arr = [10, 5, 11, 6, 20, 12]; let res = closestGreater(arr); for (let i of res) {     process.stdout.write(i + " "); } 

Output
-1 10 -1 10 -1 20 

[Expected Approach] – Using Set – O(n Log n) Time and O(n) Auxiliary Space

The idea is to use Tree Set (or Sorted Set or Set in C++) to store the elements on left of every element, ensuring that elements are stored in sorted order. Thereafter, for each element of the array arr[], find the closest greater or equal value in O(Log n) Time.

C++
#include <bits/stdc++.h> using namespace std;  // Function to find the closest greater element // on the left of every element of the array vector<int> closestGreater(vector<int> &arr) {     int n = arr.size();      // to store the results     vector<int> res(n, -1);      // to store the elements in sorted order     set<int> s;      for (int i = 0; i < n; i++) {          // First search in set         auto it = s.lower_bound(arr[i]);          // If greater or equal value exists         if (it != s.end())              res[i] = *it;          // insert the current element in the set         s.insert(arr[i]);     }          return res; }  int main() {     vector<int> arr = { 10, 5, 11, 6, 20, 12 };     vector<int> res = closestGreater(arr);     for(auto i:res) {         cout<<i<<" ";     }     return 0; } 
Java
// Function to find the closest greater element // on the left of every element of the array import java.util.TreeSet;  class GfG {      // Function to find the closest greater element     static int[] closestGreater(int[] arr) {         int n = arr.length;          // to store the results         int[] res = new int[n];         for (int i = 0; i < n; i++) {             res[i] = -1;         }          // to store the elements in sorted order         TreeSet<Integer> s = new TreeSet<>();          for (int i = 0; i < n; i++) {              // First search in set             Integer it = s.ceiling(arr[i]);              // If greater or equal value exists             if (it != null)                 res[i] = it;              // insert the current element in the set             s.add(arr[i]);         }                  return res;     }      public static void main(String[] args) {         int[] arr = {10, 5, 11, 6, 20, 12};         int[] res = closestGreater(arr);         for (int i : res) {             System.out.print(i + " ");         }     } } 
Python
# Function to find the closest greater element # on the left of every element of the array import bisect  def closestGreater(arr):     n = len(arr)      # to store the results     res = [-1] * n      # to store the elements in sorted order     s = []      for i in range(n):          # First search in set         idx = bisect.bisect_left(s, arr[i])          # If greater or equal value exists         if idx < len(s):             res[i] = s[idx]          # insert the current element in the set         bisect.insort(s, arr[i])          return res  if __name__ == "__main__":     arr = [10, 5, 11, 6, 20, 12]     res = closestGreater(arr)     for i in res:         print(i, end=" ") 
C#
// Function to find the closest greater element // on the left of every element of the array using System; using System.Collections.Generic;  class GfG {      // Function to find the closest greater element     static int[] closestGreater(int[] arr) {         int n = arr.Length;          // to store the results         int[] res = new int[n];         for (int i = 0; i < n; i++) {             res[i] = -1;         }          // to store the elements in sorted order         SortedSet<int> s = new SortedSet<int>();          for (int i = 0; i < n; i++) {              // First search in set             int? it = null;             var view = s.GetViewBetween(arr[i], int.MaxValue);             if (view.Count > 0) {                 it = view.Min;             }              // If greater or equal value exists             if (it != null)                 res[i] = it.Value;              // insert the current element in the set             s.Add(arr[i]);         }                  return res;     }      static void Main() {         int[] arr = {10, 5, 11, 6, 20, 12};         int[] res = closestGreater(arr);         foreach (int i in res) {             Console.Write(i + " ");         }     } } 
JavaScript
// Function to find the closest greater element // on the left of every element of the array function closestGreater(arr) {     let n = arr.length;      // to store the results     let res = new Array(n).fill(-1);      // to store the elements in sorted order     let s = [];      for (let i = 0; i < n; i++) {          // First search in set         let lo = 0, hi = s.length, candidate = null;         while (lo < hi) {             let mid = Math.floor((lo + hi) / 2);             if (s[mid] < arr[i])                 lo = mid + 1;             else {                 candidate = s[mid];                 hi = mid;             }         }          // If greater or equal value exists         if (candidate !== null)             res[i] = candidate;          // insert the current element in the set in sorted order         s.splice(lo, 0, arr[i]);     }      return res; }  let arr = [10, 5, 11, 6, 20, 12]; let res = closestGreater(arr); for (let i = 0; i < res.length; i++) {     process.stdout.write(res[i] + " "); } 

Output
-1 10 -1 10 -1 20 




Next Article
Find closest greater value for every element in array
author
kartik
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Find closest greater value for every element in 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, 6, 20, 12} Output : 11 6 12 10 -1 20 Input : arr[] = {10, 5, 11, 10, 20, 12} Output :z 11 10 12 11 -1 20 A simple solution is to run two
    4 min read
  • Find closest value for every element in array
    Given an array of integers, find the closest element for every element. Examples: Input : arr[] = {10, 5, 11, 6, 20, 12} Output : 11 6 12 5 12 11 Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 10 12 10 12 11 A simple solution is to run two nested loops. We pick an outer element one by one. For
    11 min read
  • Find closest smaller value for every element in array
    Given an array of integers, find the closest smaller element for every element. If there is no smaller element then print -1 Examples: Input : arr[] = {10, 5, 11, 6, 20, 12} Output : 6, -1, 10, 5, 12, 11 Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 5 -1 10 5 12 11 A simple solution is to run two
    4 min read
  • Find K closest elements to given Value in Unsorted Array
    Given an unsorted array arr[] and two numbers X and K, the task is to find K closest values to X in arr[]. Examples: Input: arr[] = {10, 2, 14, 4, 7, 6}, X = 5, K = 3 Output: 4 6 7Explanation: Three closest values of x are 4, 6 and 7. Input: arr[] = {-10, -50, 20, 17, 80}, X = 20, K = 2Output: 17 20
    12 min read
  • Find the nearest value present on the left of every array element
    Given an array arr[] of size N, the task is for each array element is to find the nearest non-equal value present on its left in the array. If no such element is found, then print -1 Examples: Input: arr[] = { 2, 1, 5, 8, 3 }Output: -1 2 2 5 2Explanation:[2], it is the only number in this prefix. He
    8 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
  • 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
  • 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
  • Replace every element with the smallest element on its left side
    Given an array of integers, the task is to replace every element with the smallest element on its left side. Note: Replace the first element with -1 as it has no element in its left. Examples: Input: arr[] = {4, 5, 2, 1, 7, 6} Output: -1 4 4 2 1 1 Since, 4 has no element in its left, so replace it b
    7 min read
  • Count elements of same value placed at same indices of two given arrays
    Given two arrays A[] and B[] of N unique elements, the task is to find the maximum number of matched elements from the two given arrays. Elements of the two arrays are matched if they are of the same value and can be placed at the same index (0-based indexing).(By right shift or left shift of the tw
    8 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