1839. Swap Place and Digit

Easy1.5 points estimatedMathsSimulationBrainteaser3 hints

A teacher writes a number whose digits are a shuffle of 1 up to the number of digits, such as 21453. Number the places from the right starting at 1. In 21453 the digit 3 sits in place 1, the digit 5 in place 2, the digit 4 in place 3, the digit 1 in place 4 and the digit 2 in place 5.

The inverse swaps the roles of place and digit: wherever the digit x sat in place i, the inverse has the digit i in place x. For 21453 that gives 23154. Given n, return its inverse. The digits of n are always a permutation of 1 to d, where d is the number of digits. Aim for O(d) time and O(1) extra space.

Example 1

Input:
n = 21453
Output:
23154
Explanation:

Each digit x in place i becomes the digit i in place x, which gives 23154.

Example 2

Input:
n = 21
Output:
21
Explanation:

Swapping place and digit gives 21 again.

Example 3

Input:
n = 3412
Output:
3412
Explanation:

This number happens to be its own inverse.

Constraints

1 ≤ n ≤ 987654321

the digits of n are a permutation of 1, 2, ..., d where d is the number of digits

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(d)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…