• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar

Pro Programming

Professional way of Programming: Learn C, C++, Java, Python, Dot Net, Android the professional way

  • Home
  • C MCQs
  • C/C++ Programs
  • Java Programs
  • C#
  • Python
  • MySQL
  • Topics
    • Arrays
    • Strings
    • Link Lists
    • Trees
    • Shapes
  • Projects
  • Articles
  • Games
You are here: Home / Archives for A program to check if a binary tree is BST or not

A program to check if a binary tree is BST or not

Ceiling in right side for every element in an array

Leave a Comment


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 right side array and find 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 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.

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);

  

        

        

        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);

    }

}

Time Complexity : O(n Log n)




If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :


thumb_up
Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.


Post navigation


Previous

first_page Frequency of each element of an array of small ranged values







Source link

Filed Under: c programming Tagged With: •   Dynamic Programming, 1s and 2s, A program to check if a binary tree is BST or not, About Us, Advanced Data Structure, Advanced Topics, Algo ▼, Algorithm Paradigms ►, Algorithms, All Algorithms, All Data Structures, Analysis of Algorithms, Aptitude, Arrange given numbers to form the biggest number | Set 1, Array, Arrays, Arrays in C/C++, Arrays in Java, AVL Tree | Set 1 (Insertion), Backtracking, Binary Search Tree, Binary Search Tree | Set 1 (Search and Insertion), Binary Search Tree | Set 2 (Delete), Binary Tree, Bit Algorithms, Block swap algorithm for array rotation, Branch & Bound, C, Campus Ambassador Program, Careers, Ceiling in a sorted array, check for pair in A[] with sum as x, Check if a given array can represent Preorder Traversal of Binary Search Tree, Closest greater element for every array element from another array, Closest greater or same value on left side for every element in array, Company Prep, Company-wise, Competitive Programming, Compiler Design, Computer Graphics, Computer Networks, Computer Organization, Computer Organization & Architecture, Contact Us, Contests, contribute.geeksforgeeks.org, contributed articles, Core Subjects ►, Count Inversions in an array | Set 1 (Using Merge Sort), Count pairs with given sum, Courses, CS Subjects, CS Subjects ▼, CS Subjectwise ►, Data Structures, DBMS, Design Patterns, Digital Electronics, Divide and Conquer, DS ▼, Engg. Mathematics, Equilibrium index of an array, Experienced Interviews, Find a triplet that sum to a given value, Find an element in array such that sum of left array is equal to sum of right array, Find duplicates in O(n) time and O(1) extra space | Set 1, Find last element after deleting every second element in array of n integers, Find subarray with given sum | Set 1 (Nonnegative Numbers), Find the Missing Number, Find the nearest smaller numbers on left side in an array, Find the smallest positive number missing from an unsorted array | Set 1, Frequency of each element of an array of small ranged values, Game Theory, GATE ▼, GATE 2019, GATE CS Corner, GATE Notes, GATE Official Papers, GBlog, GCD of more than two (or array) numbers, Geek of the Month, Geek on the Top, Geometric Algorithms, Given an array A[] and a number x, Graph, Graph Algorithms, Greedy Algorithms, Hashing, Heap, HTML & XML, ide.geeksforgeeks.org, Internship, Internship Interviews, Internships, Interview ▼, Interview Experiences, Introduction to Arrays, ISRO CS Exam, Java, Java-ArrayList, java-treeset, JavaScript, k largest(or smallest) elements in an array | added Min Heap method, 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), Languages, Languages ►, Languages ▼, Largest subarray with equal number of 0s and 1s, Largest Sum Contiguous Subarray, Last Minute Notes, Linear Search, Linked List vs Array, LinkedList, Longest Increasing Subsequence Size (N log N), Machine Learning, Majority Element, Mathematical Algorithms, Matrix, Maximum difference between two elements such that larger element appears after the smaller number, Maximum Sum Increasing Subsequence | DP-14, Maximum sum rectangle in a 2D matrix | DP-27, Maximum sum such that no two elements are adjacent, Microprocessor, Minimum number of jumps to reach end | Set 2 (O(n) solution), Minimum number of swaps required to sort an array, Multiple Choice Quizzes, Next Greater Element, Operating Systems, Pattern Searching, Perfect Sum Problem (Print all subsets with given sum), PHP, Placement Course, Practice Company Questions, Print a given matrix in spiral form, Print all possible words from phone digits, Privacy Policy, Program for array rotation, Program Output, Project, Puzzles, Pythagorean Triplet in an array, Python, Queue, Queue | Set 1 (Introduction and Array Implementation), Quizzes ▼, Randomized Algorithms, Range Query on array whose each element is XOR of index value and previous element, Recommended: Please try your approach on, Replace each element by the difference of the total size of the array and frequency of that element, Replace every array element by Bitwise Xor of previous and next element, Replace every element with the greatest element on its left side, Replace every element with the greatest element on right side, Replace every element with the smallest element on its left side, Reversal algorithm for array rotation, School Programming, Search an element in a sorted and rotated array, Searching Algorithms, Segment Tree | Set 1 (Sum of given range), set in C++, Skip to content, Sliding Window Maximum (Maximum of all subarrays of size k), Smallest Greater Element on Right Side, Software Engineering, Some rights reserved, Sort a nearly sorted (or K sorted) array, Sort an array of 0s, Sorting Algorithms, SQL, Stack, Stack Data Structure (Introduction and Program), Steps to make array empty by removing maximum and its right side, Stock Buy Sell to Maximize Profit, Strings, Students ▼, Subjective Questions, Subset Sum Problem | DP-25, Suggest a Topic, Testimonials, Theory of Computation, Top Topics, Topic-wise, Topicwise ►, Trapping Rain Water, Tree based DS ►, TreeSet ceiling() method in Java with Examples, TreeSet in Java, UGC NET CS Paper II, UGC NET CS Paper III, UGC NET Papers, Ugly Numbers, Video Tutorials, Videos, Web Technology, What’s Difference?, Write a program to reverse an array or string, Write an Article, Write Interview Experience

Primary Sidebar

Recent Posts

  • Solid State Chemistry Questions and Answers – Intensities
  • Python | Convert case of elements in a list of strings
  • Java String Array to String Example
  • 14. Two-way data binding with v-model
  • Solid State Chemistry Questions and Answers – Modern X-Ray Powder Techniques and their Applications
  • Privacy Policy
  • About
  • Contact US

© 2019 ProProgramming
 Privacy Policy About Contact Us