Ctrl K

Rise and Fall Lineup

Easy
A magician has cards numbered 0 to n, one of each, and a hint string pattern of length n made of the letters I and D. He lays all n + 1 cards in a row so that the row follows the hint: if pattern[i] is I, the card at position i is smaller than the next one, and if it is D, it is larger. There are usually several such rows, so the magician sticks to a rule: he walks through the hint from left to right and, on an I, puts down the smallest card he still holds; on a D, the largest. The final card is the only one left. Return the row he ends up with. Think about why this rule always produces a row that matches the hint.
Example 1
pattern="IIDI" → [0, 1, 4, 2, 3]

Rise: take 0, rise: 1, fall: the largest left, 4, rise: 2, and the last card left is 3. The result [0, 1, 4, 2, 3] gives 0 < 1 < 4 > 2 < 3.

Example 2
pattern="DD" → [2, 1, 0]

Two falls: take 2, then 1, and 0 is left over.

Example 3
pattern="DIDI" → [4, 0, 3, 1, 2]
Constraints
  • 1 ≤ len(pattern) ≤ 10⁶
  • Every character of pattern is I or D
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWord Topping Duel HardCake Slices for Guests EasyPalindrome With One Eraser Stroke EasyDistance to the Nearest Marker EasyGlued from the First Words Easy
loading Python…
Input
pattern="IIDI"
Expected
[0, 1, 4, 2, 3]

Run checks the first 3 tests in your browser. Submit checks all 160 tests on the server, hidden ones included.