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.

aaqib90
  • 310
  • 3
  • 14
  • 1
    Probably because it can’t properly handle characters that are longer than 1 byte. – Sebastian Simon Aug 30 '17 at 10:57
  • I would read this - https://medium.freecodecamp.org/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb. Seems you are doing nothing "wrong". perhaps ask the interviewer what their issue is :) – dijipiji Aug 30 '17 at 10:59
  • how was your loop then? – Mehdi Ben Hamida Aug 30 '17 at 10:59
  • 1
    My guess is that he has a self-perceived good answer in his mind - although it's not so good. – tibetty Aug 30 '17 at 11:01
  • Depends on the length of the string. A fairly short string (<64 chars) then a loop us quicker, anything longer and your method is quicker. I see nothing wrong with your approach. – Stuart Aug 30 '17 at 11:02
  • @Xufox Please write any string , which characters are longer than 1 byte. – aaqib90 Aug 30 '17 at 11:04
  • 1
    @MDAAQIBJAWED e.g. a string containing an emoji. – t.niese Aug 30 '17 at 11:05
  • 4
    @MDAAQIBJAWED `"Easy: "` – Sebastian Simon Aug 30 '17 at 11:06
  • Well interviewers most of the time don't want you to blindly solve a problem. But to recognize possible problems, and to clarify the use case and boundary conditions. So did you ask what the input to `stringReverse` could be and what kind of strings it should be able to handle? – t.niese Aug 30 '17 at 11:14
  • @t.niese It was simple 'abcdef'. – aaqib90 Aug 30 '17 at 11:18
  • @MDAAQIBJAWED Did you ask if it would always be that simple? Could the function get `null` or `undefined` as input, and should it handle that case and if so how? Should it deal with multi-bytes, ...? Did you ask anything about where it will be used and if there are any other requirements to that function? – t.niese Aug 30 '17 at 11:21
  • As pointed out here https://stackoverflow.com/questions/5276953/what-is-the-most-efficient-way-to-reverse-an-array-in-javascript the **reverse()** function is the culprit here and is said to be slowest. – Jeba Samuel Aug 30 '17 at 11:01

6 Answers6

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.

Ankit
  • 4,255
  • 2
  • 18
  • 22
  • 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. – Rick Hitchcock Aug 30 '17 at 11:10
  • 1
    That will be more precise agree :) however this will work well for reasonable values. – Ankit Aug 30 '17 at 11:17
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 :)

Sohum Sachdev
  • 1,276
  • 1
  • 10
  • 20
  • Recursion for such a function? I'm pretty sure that this would not be something the interviewer was looking for. – t.niese Aug 30 '17 at 11:12
  • 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). – Sohum Sachdev Aug 30 '17 at 11:17
  • 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. – t.niese Aug 30 '17 at 11:26
  • Yeah, I understand where you're coming from. But speaking from my experience, the "best answer" for a string reversal is using recursion. – Sohum Sachdev Aug 30 '17 at 11:55
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('fff'),
]);
Emil S. Jørgensen
  • 5,684
  • 1
  • 9
  • 22
0

In ECMAScript 6, you can reverse string like as below

var string = "hello";
var str = [...string].reverse().join('');
console.log(str);
Nishant Joshi
  • 225
  • 2
  • 10
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);
 }
}
Satyam Pathak
  • 4,618
  • 1
  • 17
  • 43
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);
Bishwajit
  • 55
  • 7