Sorting Sentences

Darrick Pang
2 min readFeb 5, 2021

On Tuesday February 2, I along with other fellow Flatiron graduates came together to do a mock technical interview. Four problems were given and each individual was paired up with others to solve two problems. The purpose of this was to give graduates a taste in going through an actual technical interview and brush up our skills in algorithms. I found it helpful because I know I need more practice in solving algorithms and speaking what is on my mind. Though I have gotten better, I know practice is always good.

There was one problem that I struggled to solve. The question is given a string

str = "is2 Thi1s T4est 3a", 

sort it out so that the answer is

Output: "Thi1s is2 3a T4est". 

The first step is we want to split the sentence string into an array because we want to have each individual word as a single array element. To do that, we simple say

var arr = str.split(' '). 

Notice we have space between the quotes. That is needed so the string will split between each word and not between each letter space. Otherwise, we’d get

arr = ['T', 'h',...]

instead of

arr = ['Thi1s', 'i2s',...].

Next, we want a new array called ‘sortedArray’

var sortedArray = []

to have our sentence sorted. Next, we iterate over the array twice because we we want to check if the array element has the number ‘i’. We will use indexOf() to find it. If yes, add the element to the new array. Then we repeat until it is sorted completely. The for loop is

for(i = 0; i <= array.length; i++) {
for(j = 0; j < array.length; j++) {
if(array[j].indexOf(i) >= 0) {
sortedArray.push(array[j]);
}
}
}

The full code is

function order(words){
var array = words.split(' ')
var sortedArray = []
for(i = 0; i <= array.length; i++) {
for(j = 0; j < array.length; j++) {
if(array[j].indexOf(i) >= 0) {
sortedArray.push(array[j])
}
}
}
return sortedArray.join(' ');
}

If something is not clear, let me know.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response