1331. Rank Transform of an Array
Difficulty: Easy
Topics: Array, Hash Table, Sorting
Given an array of integers arr, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
- Rank is an integer starting from 1.
- The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
- Rank should be as small as possible.
Example 1:
- Input: arr = [40,10,20,30]
- Output: [4,1,2,3]
- Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.
Example 2:
- Input: arr = [100,100,100]
- Output: [1,1,1]
- Explanation: Same elements share the same rank.
Example 3:
- Input: arr = [37,12,28,9,100,56,80,5,12]
- Output: [5,3,4,2,8,6,7,1,3]
Constraints:
- 0 5
- -109 9
Hint:
- Use a temporary array to copy the array and sort it.
- The rank of each element is the number of unique elements smaller than it in the sorted array plus one.
Solution:
We can break it down into the following steps:
- Copy and sort the array: This helps in determining the rank of each unique element.
- Use a hash map to assign ranks to elements: Since multiple elements can share the same value, a hash map (associative array in PHP) will help map each element to its rank.
- Replace the original elements with their ranks: Using the hash map, we can replace each element in the original array with its corresponding rank.
Let's implement this solution in PHP: 1331. Rank Transform of an Array
<?php /** * @param Integer[] $arr * @return Integer[] */ function arrayRankTransform($arr) { ... ... ... /** * go to ./solution.php */ } // Example usage: $arr1 = [40, 10, 20, 30]; print_r(arrayRankTransform($arr1)); // Output: [4, 1, 2, 3] $arr2 = [100, 100, 100]; print_r(arrayRankTransform($arr2)); // Output: [1, 1, 1] $arr3 = [37, 12, 28, 9, 100, 56, 80, 5, 12]; print_r(arrayRankTransform($arr3)); // Output: [5, 3, 4, 2, 8, 6, 7, 1, 3] ?>
Explanation:
-
Copy and sort the array:
- We create a copy of the input array $sorted and sort it. This helps in determining the rank of each unique element.
-
Assign ranks to elements:
- We iterate through the sorted array and use a hash map $rank to store the rank of each unique element.
- We use isset to check if an element has already been assigned a rank. If not, we assign the current rank and increment it.
-
Replace elements with their ranks:
- We then iterate through the original array and replace each element with its corresponding rank by looking it up in the $rank hash map.
Time Complexity:
- Sorting the array takes O(n log n), where n is the size of the array.
- Assigning ranks and replacing values takes O(n).
- Overall time complexity is O(n log n).
This solution efficiently handles large arrays while maintaining simplicity.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
- GitHub
The above is the detailed content of Rank Transform of an Array. For more information, please follow other related articles on the PHP Chinese website!

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
