Data Structure: Interview Experience Part 1
Data Structure: Interview Experience Part 1
-
Given a collection of distinct integers, return all possible
permutations.
Example:
Input: [1,2,3]
Output:
[[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]]
Note: Write a generic method for it
Solution:
extension Array {
func decompose() -> (Iterator.Element, [Iterator.Element])? {
guard let x = first else { return nil }
return (x, Array(self[1..<count]))
}
}
func between<T>(x: T, _ ys: [T]) -> [[T]] {
guard let (head, tail) = ys.decompose() else { return [[x]] }
return [[x] + ys] + between(x: x, tail).map { [head] + $0 }
}
func permutations<T>(xs: [T]) -> [[T]] {
guard let (head, tail) = xs.decompose() else { return [[]] }
return permutations(xs: tail).flatMap { between(x: head, $0) }
}
2. Given a collection of distinct sorted integers, search a item and return its index. If not found, return nil
Input:
[1,2,3] , 3
Output: 2
Note: Write a binary search generic function.
Solution:
func binarySearch<T:Comparable>(_ inputArr:Array<T>, _ searchItem: T) -> Int? {
var lowerIndex = 0
var upperIndex = inputArr.count - 1
while lowerIndex <= upperIndex {
let currentIndex = (lowerIndex + upperIndex)/2
if(inputArr[currentIndex] == searchItem) {
return currentIndex
} else {
if (inputArr[currentIndex] > searchItem) {
upperIndex = currentIndex - 1
} else {
lowerIndex = currentIndex + 1
}
}
}
return nil
}
3. Implement a trie.
Solution: