Last active
August 12, 2022 15:51
-
-
Save allanalves/6be632f868dfdfc38054205bf0902f0d to your computer and use it in GitHub Desktop.
Hackerrank 'Separate the Numbers' Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func separateNumbers(s: String) -> Void { | |
guard s.count > 1 else { | |
print("NO") | |
return | |
} | |
let s = Array(s) | |
guard s.count > 2 else { | |
let leftNum = s.first?.wholeNumberValue ?? 0 | |
let rightNum = s.last?.wholeNumberValue ?? 0 | |
let isAscending = leftNum > rightNum | |
print(isAscending ? "YES \(leftNum)" : "NO") | |
return | |
} | |
var substring = "" | |
var lastAdded = -1 | |
for i in 0 ... s.count / 2 { | |
substring = String(s[0...i]) | |
let num = Int(substring) ?? 0 | |
var validString = substring | |
while validString.count < s.count { | |
lastAdded = max(lastAdded, num) | |
lastAdded += 1 | |
validString += String(lastAdded) | |
} | |
if validString == String(s) { | |
print("YES \(substring)") | |
return | |
} | |
lastAdded = -1 | |
} | |
print("NO") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment