Skip to main content
LeetCode 942, Easy. Topics: Array, Two Pointers, String, Greedy. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 16 parametrized pytest cases, and a playground notebook:

Problem

A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:
  • s[i] == 'I' if perm[i] < perm[i + 1], and
  • s[i] == 'D' if perm[i] > perm[i + 1].
Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.

Examples

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is either 'I' or 'D'.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026