WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

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")


Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.