Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compact a given array problem

Tags:

arrays

Dont know whether this is a duplicate, but this was an interview question asked to me. Given an array of random numbers and -1 placed inbetween, I have to compact the array meaning all the -1s are to be replaced and the final output should be the last valid index with the fresh array. For example.

Input:
3 4 -1 -1 -1 5 8 -1 8
Output:
3 4 5 8 8 5 8 -1 8 and last valid index is 4

Input:
-1 -1 -1 -1 -1 2
Output:
2 -1 -1 -1 -1 2 and last valid index is 0

Input:
-1 -1 -1 3 3 3
Output:
3 3 3 3 3 3 and last valid index is 2

You should not swap the values just the last valid index along with the array is enough to decipher the not -1 values.

like image 330
bragboy Avatar asked Dec 29 '22 18:12

bragboy


1 Answers

int K=0
FOR i=0; i<LEN; i++
  IF arr[i]!=-1
      arr[K]=arr[i]
      K++
  END IF
RETURN K-1
like image 52
ttk Avatar answered Feb 27 '23 13:02

ttk