[Apple] Syncing Array Question

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2022-10-24Added By Anonymous
Source: Link

Company: Apple
Role: unknown
Interview Stage: unknown
Location: unknown
Year: unknown

Original Post Content:

So I was given this question and still confused what this question is about:

You are given two arrays - A is before changes and another one B is after changes. Now we are told that those changes can be insertion, reordering, or removal. There also an array C is currently equal to A and we need to update C so that C = B.

But, you can only use these 4 functions to modify C, and calls to those functions should be minimized:

- insert(at:, num:) // insert number at given index
- insert(num:) // insert number at the end of array
- remove(at:) // remove number at given index
- get(at:) // returns number at given index

For example:

Given array A [2,4,5] and B [4, 5, 6],

You need to call
C.remove(at: 0) // to remove 2 from C, C = [4, 5]
C.insert(6) // add 6 at the end of C = [4, 5, 6]

After those calls, the array in class C is now in sync with array B.

Example 2:
A: [1,2,3], B: [0, 3, 6]

Should call:
C.remove(at: 0) // C = [2, 3]
C.remove(at:0) // C= [3]
C.insert(at:0, 1) // C = [0, 3]
C.insert(num: 6) // C = [0, 3, 6] = B, condition met, stop operation

Example 3:
A: [], B [1,2,3]

Should call:
C.insert(num: 1)
C.insert(num: 2)
C.insert(num: 3)

Example 4:
A: [0, 3, 2], B [ 0, 2, 3]

Should call:
C.remove(at: 1)
C.insert(num: 3)

Limitations:

- array inside of C is private, meaning you cannot access it at all, you can only use given 4 functions to modify its element
- given invalid indices would cause a crash and therefore cannot be used for evaluation ( for example, C.get(at: index), index has to be valid otherwise the program would crash)

Question:


func syncData( arrA: [Int], arrB: [Int], arrC: C) {

\\todo

}


protocol C {
func remove( at: Int) throws
func insert(num: Int) throws
func insert(at: Int) throws
func get(at Int) throws
}

Comments