Rearrange the digits of an integer to form the largest number

Quick Overview

Given a positive integer up to 10^18, rearrange its digits to form the largest possible number and return it. The problem tests greedy reasoning about digit positions, sorting or counting digits, and keeping zeros and integer size limits in mind.

Rearrange the digits of an integer to form the largest number

Company: N26

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given a positive integer `n`, rearrange its digits to form the largest possible permutation of its digits. Return the resulting integer. ### Function Signature ```python def largest_permutation(n: int) -> int: ``` ### Constraints - `1 <= n <= 10^18` ### Examples ```text Input: n = 213 Output: 321 ``` The digits of 213 are 2, 1 and 3. In descending order they are 3, 2, 1, which forms 321. ```text Input: n = 71092 Output: 97210 ``` The digits are 7, 1, 0, 9 and 2. In descending order they are 9, 7, 2, 1, 0, which forms 97210. The zero goes last, so the result keeps all five digits. ```text Input: n = 4040 Output: 4400 ``` Each digit is used as many times as it appears in `n`. The four-digit arrangements of 4, 4, 0, 0 are 4400, 4040 and 4004, and 4400 is the largest of them.

Overview: Given a positive integer up to 10^18, rearrange its digits to form the largest possible number and return it. The problem tests greedy reasoning about digit positions, sorting or counting digits, and keeping zeros and integer size limits in mind.

N26 logo
N26
Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given a positive integer n, rearrange its digits to form the largest possible permutation of its digits.

Return the resulting integer.

Function Signature

def largest_permutation(n: int) -> int:

Constraints

  • 1 <= n <= 10^18

Examples

Input: n = 213
Output: 321

The digits of 213 are 2, 1 and 3. In descending order they are 3, 2, 1, which forms 321.

Input: n = 71092
Output: 97210

The digits are 7, 1, 0, 9 and 2. In descending order they are 9, 7, 2, 1, 0, which forms 97210. The zero goes last, so the result keeps all five digits.

Input: n = 4040
Output: 4400

Each digit is used as many times as it appears in n. The four-digit arrangements of 4, 4, 0, 0 are 4400, 4040 and 4004, and 4400 is the largest of them.