Rank of all elements in an array - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make Apps
School Guide
Python Programming
Learn To Make Apps
All Courses
TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship
Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise
Must Do Questions
DSA Topic-wise
DSA Company-wise
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Geek on the Top
Careers
Internship
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Events




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps


Practice DS & Algo.
                        


Must Do Questions

DSA Topic-wise

DSA Company-wise


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Geek on the Top

Careers

Internship


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps


School Guide


Python Programming


Learn To Make Apps


Practice DS & Algo.
                        


Must Do Questions

DSA Topic-wise

DSA Company-wise


Must Do Questions


DSA Topic-wise


DSA Company-wise


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Geek on the Top

Careers

Internship


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Geek on the Top


Careers


Internship


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Rank of an element in a stream
Rank of all elements in an array
Replace each element of Array with it’s corresponding rank
Reverse digits of an integer with overflow handled
Write a program to reverse digits of a number
Write a program to reverse an array or string
Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i
Rearrange positive and negative numbers in O(n) time and O(1) extra space
Rearrange array in alternating positive & negative items with O(1) extra space | Set 1
Rearrange array in alternating positive & negative items with O(1) extra space | Set 2
Move all zeroes to end of array
Move all zeroes to end of array | Set-2 (Using single traversal)
Minimum swaps required to bring all elements less than or equal to k together
Rearrange positive and negative numbers using inbuilt sort function
Rearrange array such that even positioned are greater than odd
Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, ..
Double the first element and move zero to end
Reorder an array according to given indexes
Arrange given numbers to form the biggest number | Set 1
Arrange given numbers to form the biggest number | Set 2
Find the largest number that can be formed with the given digits
Find next greater number with same set of digits
Arrays in Java
Largest Sum Contiguous Subarray
Program for array rotation
Arrays in C/C++
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Linear Search
Rank of an element in a stream
Rank of all elements in an array
Replace each element of Array with it’s corresponding rank
Reverse digits of an integer with overflow handled
Write a program to reverse digits of a number
Write a program to reverse an array or string
Rearrange array such that arr[i] >= arr[j] if i is even and arr[i]<=arr[j] if i is odd and j < i
Rearrange positive and negative numbers in O(n) time and O(1) extra space
Rearrange array in alternating positive & negative items with O(1) extra space | Set 1
Rearrange array in alternating positive & negative items with O(1) extra space | Set 2
Move all zeroes to end of array
Move all zeroes to end of array | Set-2 (Using single traversal)
Minimum swaps required to bring all elements less than or equal to k together
Rearrange positive and negative numbers using inbuilt sort function
Rearrange array such that even positioned are greater than odd
Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, ..
Double the first element and move zero to end
Reorder an array according to given indexes
Arrange given numbers to form the biggest number | Set 1
Arrange given numbers to form the biggest number | Set 2
Find the largest number that can be formed with the given digits
Find next greater number with same set of digits
Arrays in Java
Largest Sum Contiguous Subarray
Program for array rotation
Arrays in C/C++
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Linear Search
Difficulty Level :
Medium
giveGiven an array of N integers with duplicates allowed. All elements are ranked from 1 to N in ascending order if they are distinct. If there are say x repeated elements of a particular value then each element should be assigned a rank equal to the arithmetic mean of x consecutive ranks.Examples:  
Input : 20 30 10
Output : 2.0 3.0 1.0

Input : 10 12 15 12 10 25 12
Output : 1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0
10 is the smallest and there are two 10s so 
take the average of two consecutive ranks 
1 and 2 i.e. 1.5 . Next smallest element is 12. 
Since, two elements are already ranked, the 
next rank that can be given is 3. However, there 
are three 12's so the rank of 2 is (3+4+5) / 3 = 4.
Next smallest element is 15. There is only one 15 
so 15 gets a rank of 6 since 5 elements are ranked. 
Next element is 25 and it gets a rank of 7.

Input : 1, 2, 5, 2, 1, 60, 3
Output : 1.5, 3.5, 6.0, 3.5, 1.5, 7.0, 5.0
Explanation for first input :Method I (Simple). Consider that there are no repeated elements. In such a case the rank of each element is simply 1 + the count of smaller elements in the array. Now if the array were to contain repeated elements then modify the ranks by considering the no of equal elements too. If there are exactly r elements which are less than e and s elements which are equal to e, then e gets the rank given by  
(r + r+1 + r+2 ... r+s-1)/s 

[Separating all r's and applying 
natural number sum formula]
= (r*s + s*(s-1)/2)/s
= r + 0.5*(s-1)
Algorithm  
function rankify(A)
    N = length of A
    R is the array for storing ranks
    for i in 0..N-1
        r = 1, s = 1
        for j in 0..N-1
            if j != i and A[j] < A[i]
                r += 1
            if j != i and A[j] = A[i]
                s += 1
        // Assign Rank to A[i]
        R[i] = r + 0.5*(s-1)
    return R
Implementation of the method is given below 
C++
Java
Python3
C#
PHP
Javascript
// CPP Code to find rank of elements#include <bits/stdc++.h>using namespace std; // Function to find rankvoid rankify(int* A , int n) {     // Rank Vector    float R[n] = {0};         // Sweep through all elements in A for each    // element count the number of less than and    // equal elements separately in r and s.    for (int i = 0; i < n; i++) {        int r = 1, s = 1;                 for (int j = 0; j < n; j++) {            if (j != i && A[j] < A[i])                r += 1;                             if (j != i && A[j] == A[i])                s += 1;            }                 // Use formula to obtain rank        R[i] = r + (float)(s - 1) / (float) 2;         }         for (int i = 0; i < n; i++)        cout << R[i] << ' ';     }     // Driver Codeint main() {    int A[] = {1, 2, 5, 2, 1, 25, 2};    int n = sizeof(A) / sizeof(A[0]);         for (int i = 0; i < n; i++)    cout << A[i] << ' ';    cout << '\n';         rankify(A, n);         return 0;} // This code is contributed by Gitanjali.
// Java Code to find rank of elementspublic class GfG {         // Function to print m Maximum elements    public static void rankify(int A[], int n)    {        // Rank Vector        float R[] = new float[n];             // Sweep through all elements in A        // for each element count the number        // of less than and equal elements        // separately in r and s        for (int i = 0; i < n; i++) {            int r = 1, s = 1;                         for (int j = 0; j < n; j++)            {                if (j != i && A[j] < A[i])                    r += 1;                                     if (j != i && A[j] == A[i])                    s += 1;                }                 // Use formula to obtain  rank        R[i] = r + (float)(s - 1) / (float) 2;             }             for (int i = 0; i < n; i++)            System.out.print(R[i] + "  ");             }     // Driver code    public static void main(String args[])    {        int A[] = {1, 2, 5, 2, 1, 25, 2};        int n = A.length;              for (int i = 0; i < n; i++)            System.out.print(A[i] + "    ");            System.out.println();            rankify(A, n);    }} // This code is contributed by Swetank Modi
# Python Code to find# rank of elementsdef rankify(A):     # Rank Vector    R = [0 for x in range(len(A))]     # Sweep through all elements    # in A for each element count    # the number of less than and    # equal elements separately    # in r and s.    for i in range(len(A)):        (r, s) = (1, 1)        for j in range(len(A)):            if j != i and A[j] < A[i]:                r += 1            if j != i and A[j] == A[i]:                s += 1                      # Use formula to obtain rank        R[i] = r + (s - 1) / 2     # Return Rank Vector    return R if __name__ == "__main__":    A = [1, 2, 5, 2, 1, 25, 2]    print(A)    print(rankify(A))
// C# Code to find rank of elementsusing System; public class GfG {         // Function to print m Maximum    // elements    public static void rankify(int []A, int n)    {        // Rank Vector        float []R = new float[n];             // Sweep through all elements        // in A  for each element count        // the number  of less than and        // equal elements separately in        // r and s        for (int i = 0; i < n; i++) {            int r = 1, s = 1;                         for (int j = 0; j < n; j++)            {                if (j != i && A[j] < A[i])                    r += 1;                                     if (j != i && A[j] == A[i])                    s += 1;            }                 // Use formula to obtain rank        R[i] = r + (float)(s - 1) / (float) 2;             }             for (int i = 0; i < n; i++)            Console.Write(R[i] + " ");             }     // Driver code    public static void Main()    {        int []A = {1, 2, 5, 2, 1, 25, 2};        int n = A.Length;             for (int i = 0; i < n; i++)            Console.Write(A[i] + " ");            Console.WriteLine();            rankify(A, n);    }} // This code is contributed by vt_m.
<?php// PHP Code to find rank of elements // Function to find rankfunction rankify($A , $n){     // Rank Vector    $R = array(0);         // Sweep through all elements in A for each    // element count the number of less than and    // equal elements separately in r and s.    for ($i = 0; $i < $n; $i++)    {        $r = 1;        $s = 1;                 for ($j = 0; $j < $n; $j++)        {            if ($j != $i && $A[$j] < $A[$i])                $r += 1;                             if ($j != $i && $A[$j] == $A[$i])                $s += 1;            }                 // Use formula to obtain rank        $R[$i] = $r + (float)($s - 1) / (float) 2;         }         for ($i = 0; $i < $n; $i++)        print number_format($R[$i], 1) . ' ';} // Driver Code$A = array(1, 2, 5, 2, 1, 25, 2);$n = count($A);for ($i = 0; $i < $n; $i++)echo $A[$i] . ' ';echo "\n"; rankify($A, $n); // This code is contributed by Rajput-Ji?>
<script> // JavaScript Code to find rank of elements       // Function to find rank      function rankify(A, n) {        // Rank Vector        var R = [...Array(n)];         // Sweep through all elements in A for each        // element count the number of less than and        // equal elements separately in r and s.        for (var i = 0; i < n; i++) {          var r = 1,            s = 1;           for (var j = 0; j < n; j++) {            if (j != i && A[j] < A[i]) r += 1;             if (j != i && A[j] == A[i]) s += 1;          }           // Use formula to obtain rank          R[i] = parseFloat(r + parseFloat(s - 1) / parseFloat(2));        }         for (var i = 0; i < n; i++)          document.write(parseFloat(R[i]).toFixed(1) + "  ");      }       // Driver Code      var A = [1, 2, 5, 2, 1, 25, 2];      var n = A.length;      for (var i = 0; i < n; i++) document.write(A[i] + "  ");      document.write("<br>");      rankify(A, n);       </script>
Output: 
[1, 2, 5, 2, 1, 25, 2]
[1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0]
Time Complexity is O(N*N), while space complexity is O(1) (excluding space required to hold ranks)Method II (Efficient) In this method, create another array (T) of tuples. The first element of the tuple stores the value while the second element refers to the index of the value in the array. Then, sort T in ascending order using the first value of each tuple. Once sorted it is guaranteed that equal elements become adjacent. Then simply walk down T, find the no of adjacent elements and set ranks for each of these elements. Use the second member of each tuple to determine the indices of the values.Algorithm  
function rankify_improved(A)
    N = Length of A 
    T = Array of tuples (i,j), 
        where i = A[i] and j = i
    R = Array for storing ranks
    Sort T in ascending order 
    according to i
    
    for j in 0...N-1
        k = j 

        // Find adjacent elements
        while A[k] == A[k+1]
            k += 1 

        // No of adjacent elements
        n = k - j + 1

        // Modify rank for each
        // adjacent element
        for j in 0..n-1

            // Get the index of the
            // jth adjacent element
            index = T[i+j][1]
            R[index] = r + (n-1)*0.5

        // Skip n ranks
        r += n

        // Skip n indices
        j += n

    return R
 
The Python implementation of the method is given below  
Python3
Javascript
# Python code to find# rank of elementsdef rankify_improved(A):         # create rank vector    R = [0 for i in range(len(A))]     # Create an auxiliary array of tuples    # Each tuple stores the data as well    # as its index in A    T = [(A[i], i) for i in range(len(A))]     # T[][0] is the data and T[][1] is    # the index of data in A     # Sort T according to first element    T.sort(key=lambda x: x[0])     (rank, n, i) = (1, 1, 0)     while i < len(A):        j = i         # Get no of elements with equal rank        while j < len(A) - 1 and T[j][0] == T[j + 1][0]:            j += 1        n = j - i + 1         for j in range(n):             # For each equal element use formula            # obtain index of T[i+j][0] in A            idx = T[i+j][1]            R[idx] = rank + (n - 1) * 0.5         # Increment rank and i        rank += n        i += n     return R if __name__ == "__main__":    A = [1, 2, 5, 2, 1, 25, 2]    print(A)    print(rankify_improved(A))
<script> // JavaScript code to find// rank of elementsfunction rankify_improved(A){         // create rank vector    let R = new Array(A.length).fill(0)     // Create an auxiliary array of tuples    // Each tuple stores the data as well    // as its index in A    let T = new Array(A.length);    for(let i = 0; i < A.length; i++)    {        T[i] = [A[i], i]    }     // T[][0] is the data and T[][1] is    // the index of data in A     // Sort T according to first element    T.sort((a,b) => a[0]-b[0])     let rank = 1, n = 1,i = 0     while(i < A.length){        let j = i         // Get no of elements with equal rank        while(j < A.length - 1 && T[j][0] == T[j + 1][0])            j += 1         n = j - i + 1         for(let j=0;j<n;j++){             // For each equal element use formula            // obtain index of T[i+j][0] in A            let idx = T[i+j][1]            R[idx] = rank + (n - 1) * 0.5        }         // Increment rank and i        rank += n        i += n    }    return R} // Driver codelet A = [1, 2, 5, 2, 1, 25, 2]document.write(A,"</br>")document.write(rankify_improved(A),"</br>") // This code is contributed by shinjanpatra </script>
Output  
[1, 2, 5, 2, 1, 25, 2]
[1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0]
Time Complexity depends on the sorting procedure which is typically O(N Log N). The auxiliary space is O(N), since we need to store the indices as well as values. 
Mohit Korabu
Rajput-Ji
rdtank
statistical-algorithms
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Linked List vs Array
Python | Using 2D arrays/lists the right way