Skip to content

Print Reverse String

Logical Breakdown

  • [ ] Subproblem Identification:
  • [ ] Optimal Substructure:
  • [ ] Constraint Handling: (e.g., Modulo \(10^9 + 7\))
  • [ ] Optimization: (Matrix Exponentiation if 'A' is huge)

Mathematical Rigor

State Definition

Let \(dp[i]\) be the state for the \(i\)-th subproblem.

Recurrence Relation

\[ dp[i] = ... \]

Visualization

graph TD A["Current State"] --> B["Previous State 1"] A --> C["Previous State 2"]

Complexity Analysis

Approach Time Complexity Space Complexity
Iterative DP \(O(N)\) \(O(1)\)

Code Reference

package com.dsa.recursion;

import java.util.*;

/ * Problem: Print Reverse String * Group: 07. Recursion */ / * ============================================================================================ * PROBLEM: Print Reverse String * ============================================================================================ * * --------------------- * 1. Problem Description * --------------------- * Write a recursive function that takes a string S as input and prints the characters * of S in reverse order. * * --------------------- * 2. Logical Breakdown & Mathematical Formulation * --------------------- * Let S be a string of length N, composed of characters c_0, c_1, ..., c_{N-1}. * We define a function P(index) that prints the logical suffix starting at 'index' in reverse. * * Recurrence Relation: * To print S[i...N-1] in reverse: * 1. Recursively print S[i+1...N-1] in reverse. * 2. Print S[i]. * * Formal Definition: * P(S) = P(S.substring(1)) + print(S.charAt(0)) * * Base Case (Stopping Condition): * If S is empty (length == 0), simply return (do nothing). * * --------------------- * 3. Constraints & Complexity Analysis * --------------------- * Constraints: * 1 <= |S| <= 1000 * * Time Complexity: * O(N) - We visit every character exactly once. * * Space Complexity: * O(N) - The recursion stack will grow to depth N before the first character is printed. * * Note on Output: * The problem requires printing to Standard Output (console), not returning a new string. * * --------------------- * 4. Input / Output Format * --------------------- * Input: * - A single string S. * * Output: * - Print the characters of S in reverse order (no return value). * * --------------------- * 5. Examples * --------------------- * Input 1: * S = "scaleracademy" * Output 1: * ymedacarelacs * * Input 2: * S = "cool" * Output 2: * looc * Explanation: * Recurse('c') -> Recurse('o') -> Recurse('o') -> Recurse('l') -> Recurse('') * Return <- Print 'l' <- Print 'o' <- Print 'o' <- Print 'c' * * ============================================================================================ */

public class PrintReverseString { public int solve(int A) { return 0; }

public void printReverse(String a) {
}

}