Sitemap
Nia K

Nia K

Starter Algorithms — Reverse a String

Question: Write a method that reverses a string. Your method will receive one argument, a string, and be expected to output that string with its letters in reverse order.

2 min readNov 11, 2021

--

Input: "hello"
Output: "olleh"
Input: "apples"
Output: "selppa"

Do not call any type of built-in reverse method!

Get Nia K’s stories in your inbox

Join Medium for free to get updates from this writer.

Please solve the problem using iteration.

Press enter or click to view image in full size

JavaScript

Before you start coding

1. Understand the problem

  • given an input word, create an algorithm that will print out the word backwards

2. Write your own Test Cases

Input: "hello"
Output: "olleh"
Input: "apples"
Output: "selppa"

3. Devise a plan to solve the problem, pseudocode

  • take into account each letter of the word
  • initially assign an empty string;
    let newString = "";
  • using a for loop iterate through each letter
  • start at the last letter and print out each letter into the empty string
input str = "hello"
input str index = "h - 0, e - 1, l - 2, l - 3, o - 4"
input str length = 5
let newString = "";for loop:var i = str.length-1; // str.length - 1 = 4; this means you are starting at the 4th index and the last letter, in this case "o"i >= 0; // will run the condition as long as i is greater than or equal to 0, our initial i is 4, which is greater than and equal to 0i --;// decrement by one 1. i = 4, i >= 0, (is 4 greater than or equal to 0 - yes), i --
2. i = 3, i >= 0, (is 3 greater than or equal to 0 - yes), i --
3. i = 2, i >= 0, (is 2 greater than or equal to 0 - yes), i --
4. i = 1, i >= 0, (is 1 greater than or equal to 0 - yes), i --
5. i = 0, i >= 0, (is 0 equal to 0 - yes), i --
inside for loop:newString = newString + str[i]1. "" = "" + o
2. o = o + l
3. ol = ol + l
4. oll = oll + e
5. olle = ollo + h
6. olleh
return newString ----> "olleh"

4. Code

function reverseString(str){
let newString = "";
for (var i = str.length-1; i >= 0; i --){
newString = newString + str[i]
}
return newString
}

5. Revise

  • once you are done the problem see if you can go back and refactor the code to be more efficient
  • in this example, we can shorten the condition inside the for loop to fewer words
function reverseString(str){
let newString = "";
for (var i = str.length-1; i >= 0; i --){
newString += str[i]
}
return newString
}

--

--