SMS Message Length

function solution(S, K) {

let split = S.split(“ “)

console.log(split)

let lengths = split.map(word => word.length)

console.log(lengths)

let arr = S.split(“ “).map(word => word.length)

console.log(“arr”, arr)

let map = new Map()

let smsCount = 1

if ( Math.max(…arr) > K ) {

return -1

//if biggest item in array > K , exit with -1

}

arr.forEach((smsLength, index) => {

if (index === 0) {

map[smsCount] = smsLength

//first sms item added to map

}else {

if (map[smsCount] + smsLength + 1 <= K) {

//if first/prev item + current length + space is less than or equal to K

map[smsCount] += (smsLength + 1)

//add the new length and space to first/prev map item

} else {

smsCount += 1

//add one to count if length is too long

map[smsCount] = smsLength

//add length to new map location

}

}

})

console.log(map)

console.log(smsCount)

return smsCount

}

S = “sms messages are really short”

K = 12

solution(S, K)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store