Minimum Steps Required
Updated
Problem statement
You are given two strings str1 and str2 of the same length, made only of 0s and 1s. You change str1 step by step:
- Step 1: pick a substring of length 2 and reverse it.
- Step 2: pick a substring of length 3 and reverse it.
- In general, step
kreverses a substring of lengthk + 1.
Every step must change the string: the result must differ from the string before that step. You must do the steps in order and cannot skip one, so the last possible step reverses the whole string.
Return the smallest number of steps after which the string equals str2. If str1 already equals str2, return 0. If it is impossible, return -1.
Function
minimumStepsRequired(str1: String, str2: String) → intExamples
Example 1
str1 = "1010"str2 = "0011"return = 2Step 1 reverses "10" at indexes 2 to 3: "1010" becomes "1001". Step 2 reverses "100" at indexes 0 to 2: "1001" becomes "0011". One step is not enough, so the answer is 2.
Example 2
str1 = "1001"str2 = "0110"return = -1Step 1 can only give "0101" (reverse indexes 0 to 1) or "1010" (reverse indexes 2 to 3); reversing the middle "00" changes nothing, so it is not allowed. In step 2, every substring of length 3 in "0101" or "1010" reads the same backwards, so no step 2 changes the string. "0110" is never reached, so the answer is -1.
Example 3
str1 = "10101010"str2 = "00101011"return = 4Four steps are enough. Step 1 reverses indexes 0 to 1: "10101010" becomes "01101010". Step 2 reverses indexes 0 to 2: it becomes "11001010". Step 3 reverses indexes 0 to 3: it becomes "00111010". Step 4 reverses indexes 3 to 7: it becomes "00101011", which is str2. A full search shows no shorter sequence works, so the answer is 4.
Constraints
2 ≤ str1.length ≤ 16str2.length == str1.lengthstr1andstr2contain only0and1.
More Barclays interview questions
Similar questions at other companies
- Minimum Numeric Code TransformationAdobe · OAAdobe interview questions
- Word LadderRippling · OARippling interview questions
- Find Minimum City HopsAmazon · OA
- Shortest Path from Encoded Graph EdgesBitGo · OABitGo interview questions
- Minimum Genetic MutationBenchling · OABenchling interview questions
- Word LadderGoogle · ONSITE INTERVIEWGoogle interview questions
- Remove Invalid ParenthesesMygate · ONSITE INTERVIEWMygate interview questions
- Find Duplicate Files in a FilesystemHarvey · PHONE SCREEN · ONSITE INTERVIEWHarvey interview questions
- Shortest Word Transformation SequenceReddit · PHONE SCREENReddit interview questions
- Minimum Word Ladder LengthSalesforce · ONSITE INTERVIEWSalesforce interview questions