Submission Result: Memory Limit Exceeded even though I have correct results?

  • 1
    public class Solution {    public String reverseString(String s) {
            if (s.length() == 0)
            return " ";
            else if (s.length() == 1)
            return s;
            else {
            return reverseString(s.substring(1)) + s.substring(0,1);
        } }

    For this solution, I get "Submission Result: Memory Limit Exceeded"

    Even though it gives the right results. What gives?

  • 0

    Having Same problem with this

    public class ReverseString {
     static  void reverseString(String s) {
    String reversed="";
    int length=s.length();
    for(int i=length-1;i>=0;i--)
    //return reversed;
    public static void main(String []a)
        Scanner sc=new Scanner(;
        String s=sc.nextLine();
      //  System.out.println(s);


  • 0

    Substring would copy the designated part of the string and create a new place in the memory. s.substring always needs new memory space and is not cleaned up before exiting the code.

    I think that is the reason why you are running out of memory here. Try using StringBuilder Class, that would be faster and memory efficient.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.