Generate a Sequence by inserting positions into Array based on corresponding String value
Last Updated : 24 Mar, 2022
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', push i 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.
C++ // C++ program for above approach #include <bits/stdc++.h> using namespace std; // Function to find sequence // from given string // according to given rule void findSequence(int N, string S) { // Creating a deque deque<int> v; // Inserting N (size of string) into deque v.push_back(N); // Iterating string from behind and // pushing the indices into the deque for (int i = N - 1; i >= 0; i--) { // If letter at current index is 'F', // push i to the right of i-1 if (S[i] == 'F') { v.push_back(i); } // If letter at current index is 'B', // push i to the left of i-1 else { v.push_front(i); } } // Printing resultant sequence for (int i = 0; i <= N; i++) cout << v[i] << " "; } // Driver Code int main() { int N = 5; string S = "FBBFB"; // Printing the sequence findSequence(N, S); return 0; }
Java // JAVA program for above approach import java.util.*; class GFG { // Function to find sequence // from given string // according to given rule public static void findSequence(int N, String S) { // Creating a deque Deque<Integer> v = new ArrayDeque<Integer>(); // Inserting N (size of string) into deque v.addLast(N); // Iterating string from behind and // pushing the indices into the deque for (int i = N - 1; i >= 0; i--) { // If letter at current index is 'F', // push i to the right of i-1 if (S.charAt(i) == 'F') { v.addLast(i); } // If letter at current index is 'B', // push i to the left of i-1 else { v.addFirst(i); } } // Printing resultant sequence for (Iterator itr = v.iterator(); itr.hasNext();) { System.out.print(itr.next() + " "); } } // Driver Code public static void main(String[] args) { int N = 5; String S = "FBBFB"; // Printing the sequence findSequence(N, S); } } // This code is contributed by Taranpreet
Python3 # Python program for above approach from collections import deque # Function to find sequence # from given string # according to given rule def findSequence(N, S): # Creating a deque v = deque() # Inserting N (size of string) into deque v.append(N) # Iterating string from behind and # pushing the indices into the deque i = N - 1 while(i >= 0): # If letter at current index is 'F', # push i to the right of i-1 if (S[i] == 'F'): v.append(i) # If letter at current index is 'B', # push i to the left of i-1 else: v.appendleft(i) i -= 1 # Printing resultant sequence print(*v) # Driver Code N = 5 S = "FBBFB" # Printing the sequence findSequence(N, S) # This code is contributed by Samim Hossain Mondal.
C# // C# program for above approach using System; using System.Collections.Generic; public class GFG { // Function to find sequence // from given string // according to given rule public static void findSequence(int N, String S) { // Creating a deque List<int> v = new List<int>(); // Inserting N (size of string) into deque v.Add(N); // Iterating string from behind and // pushing the indices into the deque for (int i = N - 1; i >= 0; i--) { // If letter at current index is 'F', // push i to the right of i-1 if (S[i] == 'F') { v.Add(i); } // If letter at current index is 'B', // push i to the left of i-1 else { v.Insert(0,i); } } // Printing resultant sequence foreach (int itr in v) { Console.Write(itr + " "); } } // Driver Code public static void Main(String[] args) { int N = 5; String S = "FBBFB"; // Printing the sequence findSequence(N, S); } } // This code is contributed by 29AjayKumar
JavaScript <script> // JavaScript program for above approach // Function to find sequence // from given string // according to given rule const findSequence = (N, S) => { // Creating a deque let v = []; // Inserting N (size of string) into deque v.push(N); // Iterating string from behind and // pushing the indices into the deque for (let i = N - 1; i >= 0; i--) { // If letter at current index is 'F', // push i to the right of i-1 if (S[i] == 'F') { v.push(i); } // If letter at current index is 'B', // push i to the left of i-1 else { v.unshift(i); } } // Printing resultant sequence for (let i = 0; i <= N; i++) document.write(`${v[i]} `); } // Driver Code let N = 5; let S = "FBBFB"; // Printing the sequence findSequence(N, S); // This code is contributed by rakeshsahni </script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read