Since we have assumed the answer to be n + m long , we need to remove the extra gaps in the starting id represents the index from which the arrays xans , yans are useful
$ id = 1 ; for ( $ i = $ l ; $ i >= 1 ; $ i -- ) { if ( $ yans [ $ i ] == ' _ ' && $ xans [ $ i ] == ' _ ' ) { $ id = $ i + 1 ; break ; } }