Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutating an array without extra space

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:

enter image description here

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?

like image 516
Roni Gadot Avatar asked Apr 18 '17 13:04

Roni Gadot


People also ask

Can you mutate an array?

Arrays in JavaScript are just objects, which means they can be mutated.

How can you avoid mutating an array when performing an operation?

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.

What methods mutate array?

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.


1 Answers

  1. Scan array to determine if is it possible to store mutated array in available space -- count As and B, and check N-M >= numB-numA
  2. Walk array left to right: Shift elements to the left by the number of As so far (filling places of A)
  3. Walk array right to left: Shift elements to the right by numB-B_so_far, inserting additional Bs
like image 160
MBo Avatar answered Oct 09 '22 22:10

MBo