Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Convert an Array to reduced for using Binary Search
Next article icon

Convert an Array to reduced for using Binary Search

Last Updated : 28 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N distinct integers, the task is to convert the given array into a sequence of first N non-negative integers, i.e. [0, N - 1] such that the order of the elements is the same, i.e. 0 is placed at the index of the smallest array element, 1 at the index of the second smallest element, and so on.

Examples:

Input: arr[] = {10, 40, 20}
Output: 0 2 1

Input: arr[] = {5, 10, 40, 30, 20}
Output: 0 1 4 3 2

 

Hashing-Based Approach: Please refer to the Set 1 post of this article for the hashing-based approach. 
Time Complexity: O(N* log N)
Auxiliary Space: O(N)

Vector Of Pairs Based Approach: Please refer to the Set 2 post of this article for the approach using the vector of pairs. 
Time Complexity: O(N* log N)
Auxiliary Space: O(N)

Binary Search-based Approach: Follow the steps to solve the problem:

  • Initialize an array, say brr[] and store all the elements of the array arr[] into brr[].
  • Sort the array brr[] in ascending order.
  • Traverse the given array arr[] and for each element i.e., arr[i] find the lower_bound of arr[i] in the array brr[] and print the index of is as the result for the current element.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find the reduced form // of the given array arr[] void convert(int arr[], int n) {     // Stores the sorted form of the     // the given array arr[]     int brr[n];      for (int i = 0; i < n; i++)         brr[i] = arr[i];      // Sort the array brr[]     sort(brr, brr + n);      // Traverse the given array arr[]     for (int i = 0; i < n; i++) {          int l = 0, r = n - 1, mid;          // Perform the Binary Search         while (l <= r) {              // Calculate the value of             // mid             mid = (l + r) / 2;              if (brr[mid] == arr[i]) {                  // Print the current                 // index and break                 cout << mid << ' ';                 break;             }              // Update the value of l             else if (brr[mid] < arr[i]) {                 l = mid + 1;             }              // Update the value of r             else {                 r = mid - 1;             }         }     } }  // Driver Code int main() {     int arr[] = { 10, 20, 15, 12, 11, 50 };     int N = sizeof(arr) / sizeof(arr[0]);     convert(arr, N);      return 0; } 
Java
// Java program for the above approach import java.io.*; import java.lang.*; import java.util.*;  public class GFG {      // Function to find the reduced form     // of the given array arr[]     static void convert(int arr[], int n)     {                // Stores the sorted form of the         // the given array arr[]         int brr[] = new int[n];          for (int i = 0; i < n; i++)             brr[i] = arr[i];          // Sort the array brr[]         Arrays.sort(brr);          // Traverse the given array arr[]         for (int i = 0; i < n; i++) {              int l = 0, r = n - 1, mid;              // Perform the Binary Search             while (l <= r) {                  // Calculate the value of                 // mid                 mid = (l + r) / 2;                  if (brr[mid] == arr[i]) {                      // Print the current                     // index and break                     System.out.print(mid + " ");                     break;                 }                  // Update the value of l                 else if (brr[mid] < arr[i]) {                     l = mid + 1;                 }                  // Update the value of r                 else {                     r = mid - 1;                 }             }         }     }      // Driver Code     public static void main(String[] args)     {         int arr[] = { 10, 20, 15, 12, 11, 50 };         int N = arr.length;         convert(arr, N);     } }  // This code is contributed by Kingash. 
Python3
# Python3 program for the above approach  # Function to find the reduced form # of the given array arr[] def convert(arr, n):        # Stores the sorted form of the     # the given array arr[]     brr = [i for i in arr]      # Sort the array brr[]     brr = sorted(brr)      # Traverse the given array arr[]     for i in range(n):          l, r, mid = 0, n - 1, 0          # Perform the Binary Search         while (l <= r):              # Calculate the value of             # mid             mid = (l + r) // 2              if (brr[mid] == arr[i]):                  # Print the current                 # index and break                 print(mid,end=" ")                 break             # Update the value of l             elif (brr[mid] < arr[i]):                 l = mid + 1             # Update the value of r             else:                 r = mid - 1  # Driver Code if __name__ == '__main__':     arr=[10, 20, 15, 12, 11, 50]     N = len(arr)     convert(arr, N)      # This code is contributed by mohit kumar 29. 
C#
// C# program for the above approach using System;  class GFG{  // Function to find the reduced form // of the given array arr[] static void convert(int[] arr, int n) {          // Stores the sorted form of the     // the given array arr[]     int[] brr = new int[n];      for(int i = 0; i < n; i++)         brr[i] = arr[i];      // Sort the array brr[]     Array.Sort(brr);      // Traverse the given array arr[]     for(int i = 0; i < n; i++)     {         int l = 0, r = n - 1, mid;          // Perform the Binary Search         while (l <= r)          {                          // Calculate the value of             // mid             mid = (l + r) / 2;              if (brr[mid] == arr[i])             {                                  // Print the current                 // index and break                 Console.Write(mid + " ");                 break;             }              // Update the value of l             else if (brr[mid] < arr[i])              {                 l = mid + 1;             }              // Update the value of r             else             {                 r = mid - 1;             }         }     } }  // Driver Code public static void Main(string[] args) {     int[] arr = { 10, 20, 15, 12, 11, 50 };     int N = arr.Length;          convert(arr, N); } }  // This code is contributed by ukasp 
JavaScript
<script>  // javascript program for the above approach  // Function to find the reduced form // of the given array arr[] function convert(arr, n) {     // Stores the sorted form of the     // the given array arr[]     var brr = Array(n).fill(0);     var i;     for (i = 0; i < n; i++)         brr[i] = arr[i];      // Sort the array brr[]     brr.sort();      // Traverse the given array arr[]     for (i = 0; i < n; i++) {          var l = 0, r = n - 1, mid;          // Perform the Binary Search         while (l <= r) {              // Calculate the value of             // mid             mid = parseInt((l + r) / 2,10);              if (brr[mid] == arr[i]) {                  // Print the current                 // index and break                 document.write(mid + ' ');                 break;             }              // Update the value of l             else if (brr[mid] < arr[i]) {                 l = mid + 1;             }              // Update the value of r             else {                 r = mid - 1;             }         }     } }  // Driver Code     var arr = [10, 20, 15, 12, 11, 50];     var N = arr.length;     convert(arr, N);  // This code is contributed by SURENDRA_GANGWAR. </script> 

Output: 
0 4 3 2 1 5

 

Time Complexity: O(N * log N)
Auxiliary Space: O(N)


Next Article
Convert an Array to reduced for using Binary Search

S

shandilraunak
Improve
Article Tags :
  • Searching
  • Sorting
  • Mathematical
  • Hash
  • DSA
  • Arrays
  • Binary Search
Practice Tags :
  • Arrays
  • Binary Search
  • Hash
  • Mathematical
  • Searching
  • Sorting

Similar Reads

    Convert an Array to reduced form using Hashing
    Given an array with N distinct elements, convert the given array to a form where all elements are in the range from 0 to N-1. The order of elements is the same, i.e., 0 is placed in the place of the smallest element, 1 is placed for the second smallest element, ... N-1 is placed for the largest elem
    15+ min read
    Find a String in given Array of Strings using Binary Search
    Given a sorted array of Strings arr and a string x, The task is to find the index of x in the array using the Binary Search algorithm. If x is not present, return -1.Examples:Input: arr[] = {"contribute", "geeks", "ide", "practice"}, x = "ide"Output: 2Explanation: The String x is present at index 2.
    6 min read
    Meta Binary Search | One-Sided Binary Search
    Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta B
    9 min read
    Binary Search using pthread
    Binary search is a popular method of searching in a sorted array or list. It simply divides the list into two halves and discards the half which has zero probability of having the key. On dividing, we check the midpoint for the key and use the lower half if the key is less than the midpoint and the
    8 min read
    Binary search in an object Array for the field of an element
    What is Binary Searching?Binary searching is a type of algorithm that can quickly search through a sorted array of elements. The algorithm works by comparing the search key to the middle element of the array. If the key is larger than the middle element, the algorithm will search the right side of t
    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