VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-a-sequence-with-the-given-operations/

⇱ Generate a sequence with the given operations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate a sequence with the given operations

Last Updated : 7 Dec, 2022

Given a string which contains only (increase) and (decrease). The task is to return any permutation of integers [0, 1, ..., N] where N ? Length of S such that for all i = 0, ..., N-1

  1. If S[i] == "D", then A[i] > A[i+1]
  2. If S[i] == "I", then A[i] < A[i+1].

Note that output must contain distinct elements.

Examples: 

Input: S = "DDI" 
Output: [3, 2, 0, 1]

Input: S = "IDID" 
Output: [0, 4, 1, 3, 2] 

Approach: 

If S[0] == "I", then choose as the first element. Similarly, if S[0] == "D", then choose as the first element. Now for every operation, choose the next maximum element which hasn't been chosen before from the range [0, N], and for the operation, choose the next minimum.

Below is the implementation of the above approach:


Output
[0,4,1,3,2]

Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(n), where n is the length of the given string.

Comment