I was given the following question in an interview, and couldn't find the solution.
Given is an array of chars length n, and "important section" (all chars in this section must be saved) length m where n >= m >= 0 as follows:
Without extra space, perform the following process:
Remove all occurrences of A and duplicate all occurrences of B, return a sub array of the mutated array. For example, for the above array [C,A,X,B,B,F,Q]
n=7, m=5 ,output will be [C,X,B,B,B,B]
. Note that the mutated array length is 6, since Q was in the redundant section and B was duplicated.
Return -1 if the operation can't be performed.
Examples:
n=2, m=2 , [A,B] => [B,B]
n=2, m=2 , [B,B] => -1 (since the result [B,B,B,B] is larger then the array)
n=3, m=2 , [A,B,C] => [B,B]
n=3, m=3 , [A,B,C] => [B,B,C]
n=3, m=2 , [Z,B,A] => [Z,B,B] (since A was in the redundant section)
Looking for a code example, Could this be done in O(n) time complexity?
Arrays in JavaScript are just objects, which means they can be mutated.
We can prevent mutation of objects and arrays using the Object. freeze() JavaScript function. We pass the desired object or array as an argument to this function, which later prevents any change to the object's or array's data.
Array methods push, shift, unshift, pop, reverse, splice, sort, copyWithin, fill — simple examples. An overview of only the array methods that can mutate the original array. Some of these are already well-known, and some of them aren't used as often.
A
s and B
, and check N-M >= numB-numA
A
s so far (filling places of A) numB-B_so_far
, inserting additional B
sIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With