HackerRank Array left rotation using Swift I solve this problem in Swift. Looking for feedback on my code or a better solution:



import Foundation

// parses line to return array of numbers in string format
func readIntegers() -&gt; [String] {
    return readLine()!.componentsSeparatedByString(" ").map { $0 }
}

// left rotates the array by a given input
func leftRotation() -&gt; String {
    let input = readIntegers()
    let array = readIntegers()
    var newArray = [String](count: Int(input[0])!, repeatedValue: "")
    let (count, rotations) = (Int(input[0])!, Int(input[1])!)

    for index in 0..&lt;count {
        // newIndex after rotation
        let newIndex = index + rotations
        if newIndex &lt; count  { // up until count
            newArray[index] = array[newIndex]
        } else { // loops back to beginning index of array
            newArray[index] = array[newIndex - count]
        }
    }
    // joins the array
    return newArray.joinWithSeparator(" ")
}

print(leftRotation())
I am not a swift programmer so i will not be able to give you exact advice on how to improve the quality of your code but rather the algorithm you used to solve this challenge and nitpicks i have with your solution.

Firstly lets look at the question itself.

It asks you to print out the new array. why are you creating it and turning it back into a string?

That considered, you can simply perform 2 for loops

1 for loop up until the "break" where the array has overflown, and a second for loop for the rest of the untouched array.



therfor we can simply print out the elements at location 

d to n


and then the elements from 

0 to d


This will shorten your code considerably and make it run a whole lot faster because no extra variables are needed and you arent doing array manipilation, its just a way to iterate over an array