CodingEasy Strings

Reverse a String

Asked for all developer roles

Why they ask this: A quick check of loops, indexes and the difference between bytes and characters.

Problem

Write a function that returns the reverse of a string. Try it without using a built-in reverse helper first.

Example

text
Input:  "hello"
Output: "olleh"

Input:  "TechHire"
Output: "eriHhceT"

Hints

    Approach

    Convert the string into an array of characters, then swap chars[left] and chars[right] while left < right, moving both pointers inwards. Join the array back into a string.

    Unicode note: str.split('') in JavaScript splits UTF-16 code units and PHP's strrev() reverses bytes, so both break emoji or multi-byte text. [...str] and mb_str_split() split by code point, which is fine for most text. Devanagari letters with vowel signs (such as "की") are several code points; reversing those perfectly needs grapheme-aware splitting (Intl.Segmenter in JavaScript, grapheme_* functions in PHP).

    Solution

    js
    function reverseString(str) {
      const chars = [...str]; // split by code point, not UTF-16 unit
      let left = 0;
      let right = chars.length - 1;
    
      while (left < right) {
        [chars[left], chars[right]] = [chars[right], chars[left]];
        left++;
        right--;
      }
    
      return chars.join('');
    }
    
    console.log(reverseString('hello')); // "olleh"
    Time O(n) Space O(n)

    Can you explain this in your own words?

    Back to coding practice