rank transform of an array
I was at a friend's bachelor party for the last ~week, so this is me getting back on the horse.
problem #
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.
Input: arr = [40,10,20,30]
Output: [4,1,2,3]
Input: arr = [100,100,100]
Output: [1,1,1]
original solution #
- turn the array into a set to de-duplicate entries, and sort that
- use that set to make a mapping from int -> order (index + 1)
- return arr, where each element (key) is replaced by the order (value) from the map
class Solution:
def arrayRankTransform(self, arr: List[int]) -> List[int]:
sorted_set = sorted(set(arr))
ranking = {i: index + 1 for index, i in enumerate(sorted_set)}
return [ranking[i] for i in arr]
This one was simple, took about 2 minutes.
fixed solution #
None today. This one was easy.
81% speed, but the distribution is pretty normal. No distinct humps means the differences are micro optimizations.
- Previous: sum of prefix scores of strings
- Next: debugging a zig tui with lldb