UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Swift Coding Challenges: Find longest prefix

Forums > Books

In the book Swift Coding Challenges, Chapter 12: Find longest prefix, the challenge is to "Write a function that accepts a string of words with a similar prefix, separated by spaces, and returns the longest substring that prefixes all words.

The book provided the following solution:

func challenge12(input: String) -> String {
    let parts = input.components(separatedBy: " ")
    guard let first = parts.first else { return "" }

    var currentPrefix = ""
    var bestPrefix = ""

    for letter in first {

        for word in parts {
            if !word.hasPrefix(currentPrefix) {
                return bestPrefix

        bestPrefix = currentPrefix

    return bestPrefix

I chose another approach. Could you offer critique on my approach compared with the given solution? Thanks !

func challenge12(input: String) -> String {

    var words = input.components(separatedBy: " ")
    words.sort(){$0.count < $1.count}
    var prefix = words[0]
    for i in 1..<words.count {
        prefix = prefix.commonPrefix(with: words[i])
        guard prefix.count > 0 else {return ""}
    return prefix
print(challenge12(input: "swift switch swill swim"))
print(challenge12(input: "flip flap flop"))
assert(challenge12(input: "swift switch swill swim") == "swi", "failed test")
assert(challenge12(input: "flip flap flop") == "fl", "failed test")


Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.