Skip to content

Instantly share code, notes, and snippets.

@orkoden orkoden/demotask.swift
Last active Apr 23, 2019

Embed
What would you like to do?
swift solution to codility demo task
// MissingInteger
// Find the smallest positive integer that does not occur in a given sequence.
//This is a demo task.
//
//Write a function:
//
//public func solution(_ A : inout [Int]) -> Int
//
//that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
//
//For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
//
//Given A = [1, 2, 3], the function should return 4.
//
//Given A = [−1, −3], the function should return 1.
//
//Write an efficient algorithm for the following assumptions:
//
//N is an integer within the range [1..100,000];
//each element of array A is an integer within the range [−1,000,000..1,000,000].
//
let A = [1, 3, 6, 4, 1, 2]
let A2 = [1, 2, 3]
let A3 = [-1, -3]
public func solution(_ a : [Int]) -> Int {
let noNegative = a.filter { $0 > 0 }
let uniqueNumbers = Set(noNegative)
var uniqueArray = Array(uniqueNumbers)
uniqueArray.sort()
for (index, number) in uniqueArray.enumerated() {
if number > index + 1 {
return index + 1
}
}
let largestIntNotPresent = (uniqueArray.last ?? 0) + 1
return largestIntNotPresent
}
let a = solution(A)
let a2 = solution(A2)
let a3 = solution(A3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.