Final state of the string after modification | C ++ implementation of above approach ; Function to return final positions of the boxes ; Populate forces going from left to right ; Populate forces going from right to left ; return final state of boxes ; Driver code ; Function call to print answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; string pushBoxes ( string S ) { int N = S . length ( ) ; vector < int > force ( N , 0 ) ; int f = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ' R ' ) { f = N ; } else if ( S [ i ] == ' L ' ) { f = 0 ; } else { f = max ( f - 1 , 0 ) ; } force [ i ] += f ; } f = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( S [ i ] == ' L ' ) { f = N ; } else if ( S [ i ] == ' R ' ) { f = 0 ; } else { f = max ( f - 1 , 0 ) ; } force [ i ] -= f ; } string ans ; for ( int f : force ) { ans += f == 0 ? ' . ' : f > 0 ? ' R ' : ' L ' ; } return ans ; } int main ( ) { string S = " . L . R . . . LR . . L . . " ; cout << pushBoxes ( S ) ; }