1

I have one newArray and one oldArray as follows. If newArray has anyitem which exists in the oldArray, then I want to delete it from oldArray. I could able to run two nested for loop and detect duplicates to remove, but it will be O(n2). I wonder if there is a better way to handle?

I cannot use Set, because order needs to be kept.

newArray = [2,4,5]

oldArray = [1,2,3,5]

newArray = [2,4,5,1,3] // append newArray and oldArray.

casillas
  • 16,351
  • 19
  • 115
  • 215
  • Are you simply appending `oldArray` to `newArray` but without any duplicates? – rmaddy May 06 '19 at 16:32
  • The one of the first array. – fphilipe May 06 '19 at 16:32
  • @rmaddy, yes I am trying to append `newArray` with `oldArray`. `newArray` has priority on `oldArray` in terms of duplication. – casillas May 06 '19 at 16:34
  • The problem description conflicts with the quoted output. The way you describe it, the output would be: `newArray = [2, 4, 5] /* no change */` `oldArray = [1, 3]` `/* mutated */` `/* That's it, there's no mention of a 3rd array */`. Please clarify. – BaseZen May 06 '19 at 16:34
  • See https://stackoverflow.com/questions/25738817/removing-duplicate-elements-from-an-array-in-swift about removing duplicates in `O(n)` using a `Set`. – Sulthan May 06 '19 at 16:40

1 Answers1

3

Maybe you should use Set after all! Set containment is fast! https://developer.apple.com/documentation/swift/set/1540013-contains

 let setFirst = Set(first)
 var merge = first
 second.forEach { v in
     if !setFirst.contains(v) {
         merge.append(v)
     }
 }
 print(merge)

MINOR ADDENDUM

For the enthusiasts of functional style and compact syntax:

let funcMerge = first + second.filter { !setFirst.contains($0) }
BaseZen
  • 8,650
  • 3
  • 35
  • 47
  • The latter code example is certain better. I wouldn't even entertain the first as an option for production code (good for instruction though, to show what happens "behind the scenes") – Alexander May 07 '19 at 02:23