# Give the inverse permutation

Given a finite permutation output its inverse.

You may take input and output in any reasonable format equivalent to a list of natural numbers. You may choose to use 0 indexing or 1 indexing. Your input and output format should be the same. You may assume a permutation has at least 1 element.

This is so the goal is to minimize the size of your source as measured in bytes.

## Permutations

A finite permutation is a function which takes an $$\n\$$-tuple and produces an $$\n\$$-tuple such that every element of the input is present in the output, and the ordering does not rely on the values of the inputs.

We can unambiguously represent these permutations with an $$\n\$$-tuple where each element is the index of where it will end up. For example:

$$(3 \,\, 2 \,\, 1 \,\, 0)$$

This permutation reverses a $$\4\$$ element tuple. The first element goes to the 3rd (last) position, the second goes to the 2nd (penultimate) position etc.

With this representation a valid permutation is just any list of size $$\n\$$ which contains the numbers $$\0\$$ through $$\n-1\$$.

For a permutation $$\A\$$ the inverse permutation of $$\A\$$ is a permutation such that when applied after $$\A\$$ it restores the list to it's initial state.

For example $$\(3\,\,2\,\,1\,\,0)\$$ is the permutation that reverse the order of 4 elements. It is its own inverse since reversing twice gets you back to where you started. $$\(1\,\,2\,\,3\,\,4\,\,0)\$$ takes the first of 5 elements and moves it to the end, it has an inverse of $$\(4\,\,0\,\,1\,\,2\,\,3)\$$ since that takes the last of 5 elements and moves it to the front:

$$(A,B,C,D,E) \\ \underset{\,(1\,\,2\,\,3\,\,4\,\,0)\,}{\xrightarrow{}}\\ (B,C,D,E,A) \\ \underset{\,(4\,\,0\,\,1\,\,2\,\,3)\,}{\xrightarrow{}}\\ (A,B,C,D,E)$$

Every permutation has an inverse.

## Test cases

[0] -> [0]
[0,1,2] -> [0,1,2]
[2,1,0] -> [2,1,0]
[1,2,0] -> [2,0,1]
[0,2,1] -> [0,2,1]
[1,2,0,5,4,3] -> [2,0,1,5,4,3]

• A bit surprised I couldn't find this question already. If someone does, let me know and I'll be happy to close this. Commented Feb 26, 2022 at 12:49
• Does this answer your question? codegolf.stackexchange.com/questions/136637/… Commented Feb 26, 2022 at 14:03
• Does this answer your question? Get the indices of an array after sorting Commented Feb 26, 2022 at 14:20
• @pxeger I'm tempted to say yes. But that is more general seeing as it's not restricted to permutations. If you have a builtin that does that, it works here. But if you don't have a way to sort by indices, or to sort at all there are other viable approaches that exploit the restrictions to permutations. Sorting can be pretty expensive if you don't have a built in and this challenge doesn't require sorting. Commented Feb 26, 2022 at 14:24
• Also compare the two python (without numpy) approaches. Since this one has a uniqueness guarantee it can be a lot shorter. Commented Feb 26, 2022 at 14:26

# R, 5 bytes

order


Try it online!

# R, 26 bytes

function(x)match(seq(x),x)


Try it online!

Both 1-indexed.

# JavaScript (ES6), 28 bytes

Modifies the input list in-place.

a=>[...a].map((v,i)=>a[v]=i)


Try it online!

# MATL, 2 bytes

&S


Try it online!

Built-in, 1-indexed.

Get the second output of sort. Implicit input, implicit output.

### MATL, 4 bytes

fG&m


Try it online!

Just to make use of the "restricted to permutations" aspect of this question (mentioned in the question comments). Construct an array of 1:length(input), and find the position of each element of that in the input array.

Another option at 6 bytes: t"X@@(

# Wolfram Language (Mathematica), 8 bytes

Ordering


Try it online! 1-indexed (while the input can be either 0- or 1-indexed, the output is always 1-indexed). Plot twist: this generic builtin beats the specific builtin InversePermutation (not to mention that that builtin operates on Mathematica's custom permutation type, which would be hard to justify as being "equivalent to a list of natural numbers").

# K (ngn/k), 7 1 bytes

<


built in.
old answer {x?!#x}

Try it online!

### Explanation

{x?!#x}   a function that takes a list x
x?       indices of the elements in x
!#x    in the range to length x


# Python 3, 35 31 bytes

lambda l:map(l.index,sorted(l))


Try it online!

Thanks to Jonathan Allan for the -4 bytes!

• range(len(l)) can be sorted(l) for -4. Commented Feb 26, 2022 at 13:43

# Python 3 NumPy (not using builtin), 23 bytes

lambda L:L.put(L[L],+L)


Try it online!

Expects a numpy array and modifies it in-place.

# Python 3 NumPy (not using builtin), 29 bytes

lambda L:sorted(L,key=L.item)


Try it online!

This doesn't really use numpy except for the shorter item member which replaces the cumbersome __getitem__

# Python 3 NumPy (builtin), 20 bytes

lambda L:L.argsort()


Try it online!

This one requires the input to be a numpy array.

# Python 3 NumPy (builtin), 26 bytes

from numpy import*
argsort


Try it online!

# Builtin solutions

### APL / BQN, 1 byte

⍋


### J, 2 bytes

/:


Try it online!

### Jelly, 1 byte

Ụ


Try it online! (1-indexed)

# Factor, 8 bytes

arg-sort


Try it online!

# Pari/GP, 16 bytes

p->vecsort(p,,1)


Try it online!

# Retina 0.8.2, 56 bytes

\d+
$* (?<=(?=(1*,)*(?<-2>1)*(?(2)^)(?!1))^(1*,)*)1*$#1


Try it online! Link includes test cases. Explanation:

\d+
$*  Convert to unary. 1*  For each element... (?<=^(1*,)*)  ... find its index, ... (?=(1*,)*(?<-2>1)*(?(2)^)(?!1))  ... then find the index of the element with that as its value. $#1


Replace the element with that index (in decimal).

# Julia 1.0, 8 bytes

sortperm


Try it online!

1-indexed

# flax, 1 byte

⍋


Builtin \o/

Unlike Jelly, flax is 0-indexed.

# Desmos, 20 bytes

f(l)=sort(sort(l),l)


Try It Desmos!

Try It Desmos! - Prettified

• I believe you can remove the last parentheses ). Commented Feb 27, 2022 at 13:42
• @PyGamer0 No, it gives an error. Commented Feb 27, 2022 at 23:59

# x86-64 machine code, 11 bytes

8B 04 96 89 14 87 FF CA 79 F6 C3


Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as an array of 32-bit integers; the address of the given permutation, as an array of 32-bit integers, in RSI; and the length of that array in EDX. The starting point is after the first 6 bytes.

In assembly:

r:  mov eax, [rsi+4*rdx]    # Load the entry at index EDX into EAX.
mov [rdi+4*rax], edx    # Store the value of EDX into the result array at index EAX.
f:  dec edx     # (Start here.) Count down from the length in EDX.
jns r       # Jump back if it isn't negative. (This will iterate from n-1 to 0.)
ret         # Return.


# 05AB1E, 2 bytes

{k


0-based.

Explanation:

{   # Sort the (implicit) input-list
k  # Get the 0-based indices of each value in the (implicit) input-list
# (after which the list is output implicitly as result)


import Data.List
f p=snd<$>sort(zip p[0..])  Try it online! Alternative 47 bytes using association list. • saved 7 Bytes thanks to @Unrelated String • added a maybe() to convert maybe int to just int, if a just int is acceptable it can be 37 Bytes. f p|i<-zip p[0..]=maybe 0id.(lookupi).snd<$>i


Try it online!

• -7 on the second version? Commented Feb 28, 2022 at 18:10
• Nice one @Unrelated String , although Idk if a just int is valid I thought it was interesting to add that Commented Mar 1, 2022 at 7:35

# Python3, 27 bytes

def f(l):return l.argsort()


Try it online!

• Welcome to Code Golf, and nice answer! Commented Mar 3, 2022 at 3:40

# Vyxal, 1 byte

⇧


Try it Online!

I suppose grading the list up also works.

## Vyxal, 9 bytes

Ṗ'2(?~İ)⁼


Try it Online!

## Explained

Ṗ'2(?~İ)⁼
Ṗ         # From all permutations of the input
'        # Keep those where
2(      #   Getting the result of
?~İ    #   [input[x] for x on tos]
)   #   twice
⁼  #   equals the original item.


# Charcoal, 6 bytes

ＩＥθ⌕θκ


Try it online! Link is to verbose version of code. Explanation:

  θ     Input array
Ｅ      Map over elements
⌕    Find index of
κ  Current index
θ   In input array
Ｉ       Cast to string
Implicitly print