← Java roadmap

Topic 25 of 30 · Beginner

Reverse Unicode code points in Java

Return a new string with Unicode code points reversed, without splitting surrogate pairs.

BeginnerFreshers · 0 yearsStrings

Java 17+; compile each complete program as Main.java.

Problem statement

Return a new string with Unicode code points reversed, without splitting surrogate pairs.

A text transformation needs code-point rather than UTF-16 char reversal.

Input: Non-null String.

Output: Reversed String.

  • Length <= 100000 code points.
  • Grapheme clusters are not preserved.

Sample 1

Input: campus
Output: supmac

ASCII code points reverse normally.

Sample 2

Input: A😀
Output: 😀A

The supplementary code point remains intact.

Brute-force solution

Prepend each code point to an immutable result, creating repeated intermediate strings.

O(n)


class Main {
static String reverse(String text){int[] a=text.codePoints().toArray();StringBuilder out=new StringBuilder();for(int i=a.length-1;i>=0;i--)out.appendCodePoint(a[i]);return out.toString();}
public static void main(String[] args) throws Exception {
System.out.println(reverse("campus"));
if(!reverse("campus").equals("supmac") || !reverse("").equals(""))throw new AssertionError();
}
}
Optimized solution

Read code points into an array and append backward to a StringBuilder.

  1. Extract code points.
  2. Visit from last to first.
  3. Append with appendCodePoint.

class Main {
static String reverse(String text){int[] a=text.codePoints().toArray();StringBuilder out=new StringBuilder();for(int i=a.length-1;i>=0;i--)out.appendCodePoint(a[i]);return out.toString();}
public static void main(String[] args) throws Exception {
System.out.println(reverse("campus"));
if(!reverse("campus").equals("supmac") || !reverse("").equals(""))throw new AssertionError();
}
}
Complexity analysis

Time: O(n)

Auxiliary space: O(n)

Test cases
  • Empty string.
  • Supplementary Unicode.
  • Combining marks.
Add to main: if(!reverse("A😀").equals("😀A")) throw new AssertionError();
Common mistakes
  • Reversing char values and splitting surrogate pairs.
  • Claiming grapheme-aware output.
Key takeaways
  • State Unicode semantics.
  • Use appendCodePoint.
  • Avoid repeated immutable concatenation.
Follow-up challenges
  • How would you reverse user-perceived graphemes?
  • How do char and code point counts differ?
Practise Java with the AI mentor

Can't find a Java topic you need for exams or placements? Request it and we'll add it.