VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-a-sequence-by-inserting-positions-into-array-based-on-corresponding-string-value/

⇱ Generate a Sequence by inserting positions into Array based on corresponding String value - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate a Sequence by inserting positions into Array based on corresponding String value

Last Updated : 23 Jul, 2025

Given a string S of length N. The string consists only of letters 'F' and 'B'. The task is to generate a sequence performing some operations such that:

  • Consider an integer sequence A that consists of only a 0, i.e. A = (0).
  • Now, for each index(i) of the string (1 to N), if S[i] is 'F' add i to the immediate front (i.e. left side) of i-1 in sequence A
  • Else if S[i] is 'B' add i to the immediate back (i.e. right side) of i-1 sequence A.
  • Print the resultant sequence A.

Examples :

Input: N = 5, S = "FBBFB"
Output: 1 2 4 5 3 0
Explanation: Initially, A = {0}.
S[1] is 'F' , sequence becomes {1, 0}
S[2] is 'B' , sequence becomes {1, 2, 0}
S[3] is 'B' , sequence becomes {1, 2, 3, 0}
S[4] is 'F' , sequence becomes {1, 2, 4, 3, 0}
S[5] is 'B' , sequence becomes {1, 2, 4, 5, 3, 0}

Input : N = 6 , S = "BBBBBB"
Output : 0 1 2 3 4 5 6

Approach: The idea to solve the problem is based on the concept dequeue. 

As at each iteration, it is possible that insertion of i may occur from any end of (i-1), therefore deque can be used as in dequeue insertion is possible from any end. 

Follow the steps for the solution:

  • The observation in the approach is that the problem becomes more simple after inverting all the operations.
  • The problem now modifies to, a given sequence that consists of only (N), and after each iteration from the end of the string,
    • If S[i] is 'F', pushi to the right of i-1,
    • If S[i] is 'B', push i to the left of i-1 in the dequeue.
  • Return the elements of dequeue in the order from the front end.

Below is the implementation of the above approach.

 
 


Output
1 2 4 5 3 0 


 

Time Complexity: O(N)
Auxiliary Space: O(N)


 

Comment