0
function stringReverse(str){
    return str.split('').reverse().join('');
}

In an interview, i was asked to reverse a string. I solved it by above code but my interviewer said this is a bad solution. Then i used loop but he was not happy.

function stringReverse(str){
    var a = str.split(''), b=[];
    for(var i=0;i<arr.length;i++){
       b.push(a[a.length-1-i]);
    }
    return b.join('');
}

Please add your comments.

12
  • 1
    Probably because it can’t properly handle characters that are longer than 1 byte. Commented Aug 30, 2017 at 10:57
  • I would read this - medium.freecodecamp.org/…. Seems you are doing nothing "wrong". perhaps ask the interviewer what their issue is :) Commented Aug 30, 2017 at 10:59
  • 1
    My guess is that he has a self-perceived good answer in his mind - although it's not so good. Commented Aug 30, 2017 at 11:01
  • 1
    @MDAAQIBJAWED e.g. a string containing an emoji. Commented Aug 30, 2017 at 11:05
  • 4
    @MDAAQIBJAWED "Easy: 😎" Commented Aug 30, 2017 at 11:06

6 Answers 6

4

May be interviewer wanted you to handle null, undefined or blank string

without this check your code might throw this exception

Cannot read property 'split' of undefined

use this :

if( str) {
str.split('').reverse().join('')
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

OR more specifically :

if( str && (typeof str == 'string') ) {
   // do something
}

refer this SO post for more details.

Sign up to request clarification or add additional context in comments.

2 Comments

May be best to explicitly test for a string: if(typeof str == 'string'). Otherwise, an error would be thrown if the value is an object, number, etc.
That will be more precise agree :) however this will work well for reasonable values.
1

There are two possible ways your interviewer might not have been happy with your answer.

  1. From my experience, when an interviewer asks you to reverse a string, you shouldn't use the existing functions for it. You should implement it from scratch. In your case, a nice approach would be to use recursion to solve the problem. Look at this link!

  2. Performance issues! Using the reverse function is not the fastest way to reverse a string. Check this out!

Hope this solved your questions :)

5 Comments

Recursion for such a function? I'm pretty sure that this would not be something the interviewer was looking for.
Yes, recursion. This is a very common interview question where the interviewer wants you to use recursion for this sort of problem. This would be O(log n).
If the interviewer explicitly asks for recursion, then maybe, but even then I would be suspicious, and ask why a recursive function should be used. I most surly would be shocked about a recursive solution for this task, if I wouldn't have asked explicitly to solve it with recursion or in a uncommon creative way.
Yeah, I understand where you're coming from. But speaking from my experience, the "best answer" for a string reversal is using recursion.
I think the best answer is walking the array, either copying to a new array or swapping in place. The OP's answer is wasteful because of all the allocations.
1

This article deals with unicode symbols in JavaScript: JavaScript has a Unicode problem · Mathias Bynens

The best solution to your problem uses the Array.from method which works in all browsers except from Internet Explorer (MDN has a polyfill for that).

Here is a solution based on the articles answer to reverse a string:

function strReverse(str) {
  //Only allow numbers and strings to pass, else return empty string
  if (typeof str != 'string' && typeof str != 'number') {
    return '';
  }
  //Return the reversed string
  return Array.from(str.toString()).reverse().join('');
}
//TESTS
console.log([
  strReverse(),
  strReverse(null),
  strReverse("null"),
  strReverse(true),
  strReverse("▼ ▼▲ ▼"),
  strReverse(1138),
  strReverse('𝌆'),
  strReverse('f𝌆ff𝐀'),
]);

Comments

0

In ECMAScript 6, you can reverse string like as below

var string = "hello";
var str = [...string].reverse().join('');
console.log(str);

Comments

0

When I was in 10th standard, Our computer teacher always asks every student to write a code to check if the given string is palindrome or not.

Palindrome string is a string which is always same as its reverse ex: mom = mom

In an interview, if someone asked you to write a code to reverse a string. Then he wants to see your logical approach to solve the problem. Existing function in any programming language has also code which actually put a logical approach and solves the problem.

Reverse code in java

import java.util.*;

class Reverse
{
  public static void main(String args[])
{
   String original, reverse = "";
   Scanner in = new Scanner(System.in);
   System.out.println("Enter a string to get reverse");
   original = in.nextLine();
   int length = original.length();
   for ( int i = length - 1; i >= 0; i-- )
     reverse = reverse + original.charAt(i);
 }
}

Comments

0
String words[] = str.split("\\s");
    String rev = "";
    for (String w : words) {
        StringBuilder sb = new StringBuilder(w);
        sb.reverse();
        rev += sb.toString() + " ";
    }
    System.out.println("\n reverse string=" + rev);

4 Comments

This might be correct, but it's in java while the question was about javascript unfortunately.
oh yes !! i dint notice that yu need in javascript..Lemme try for it, come back.
Still working on that?
no Casey, did not get time to work on it. But I see people have already worked on it and given an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.