Back to Practice Dashboard
Python BasicsMedium

Program to calculate length of string using recursion

Learn how to solve the 'Program to calculate length of string using recursion' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Medium

Write a function string_length(s) that calculates and returns the length of the string s using recursion. You must NOT use the built-in len() function. The base case is an empty string which has length 0. For each recursive call, count one character and recurse on the remaining string.

Constraints
  • 0 <= len(s) <= 1000
  • s contains only printable ASCII characters

Examples

Example 1
Input
s = 'hello'
Output
5
Explanation

The string 'hello' has 5 characters: h, e, l, l, o.

Example 2
Input
s = 'python'
Output
6
Explanation

The string 'python' has 6 characters.

Example 3
Input
s = ''
Output
0
Explanation

An empty string has length 0.

Need a Hint?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor